Skip to content
Draft
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
21 changes: 21 additions & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<Project>
<PropertyGroup>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>

<ItemGroup>
<!-- Direct vulnerable dependencies for demonstration -->
<PackageVersion Include="Newtonsoft.Json" Version="10.0.1" />
<PackageVersion Include="NLog" Version="4.4.0" />
<PackageVersion Include="System.IdentityModel.Tokens.Jwt" Version="5.1.0" />
<PackageVersion Include="Microsoft.Data.SqlClient" Version="1.0.19239.1" />

<!-- Dependencies that will bring in vulnerable transitive dependencies -->
<PackageVersion Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.0" />
<PackageVersion Include="Microsoft.Extensions.Logging.Console" Version="3.1.0" />

<!-- Standard packages for functionality -->
<PackageVersion Include="Microsoft.AspNetCore.OpenApi" Version="8.0.0" />
<PackageVersion Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>
</Project>
113 changes: 111 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,111 @@
# vulnerable-dependencies
Simulates a repository with multiple projects, CPM, and vulnerable direct and transitive dependencies
# Vulnerable Dependencies Sample

This repository demonstrates a .NET 8 solution with multiple projects that include various vulnerable direct and transitive dependencies, managed through Central Package Management (CPM).

## Purpose

This sample showcases:
- **Direct vulnerable dependencies**: Packages directly referenced in projects that have known security vulnerabilities
- **Transitive vulnerable dependencies**: Vulnerable packages that are pulled in as dependencies of other packages
- **Central Package Management**: Centralized package version management using `Directory.Packages.props`
- **Security scanning**: How .NET detects and reports vulnerable packages during build/restore

## Solution Structure

```
├── VulnerableDependencies.sln
├── Directory.Packages.props # Central Package Management configuration
└── src/
├── VulnerableWebApi/ # ASP.NET Core Web API with vulnerable packages
├── VulnerableLibrary/ # Class library with vulnerable dependencies
└── VulnerableConsole/ # Console application with vulnerable packages
```

## Vulnerable Dependencies Included

### Direct Vulnerable Dependencies

| Package | Version | Severity | CVE/Advisory | Project |
|---------|---------|----------|--------------|---------|
| `Newtonsoft.Json` | 10.0.1 | High | [GHSA-5crp-9r3c-p9vr](https://github.com/advisories/GHSA-5crp-9r3c-p9vr) | VulnerableWebApi |
| `NLog` | 4.4.0 | Various | Multiple vulnerabilities | VulnerableLibrary |
| `System.IdentityModel.Tokens.Jwt` | 5.1.0 | Moderate | [GHSA-59j7-ghrg-fj52](https://github.com/advisories/GHSA-59j7-ghrg-fj52) | VulnerableLibrary |
| `Microsoft.Data.SqlClient` | 1.0.19239.1 | High/Moderate | Multiple ([GHSA-8g2p-5pqh-5jmc](https://github.com/advisories/GHSA-8g2p-5pqh-5jmc), [GHSA-98g6-xh36-x2p7](https://github.com/advisories/GHSA-98g6-xh36-x2p7)) | VulnerableConsole |

### Packages with Vulnerable Transitive Dependencies

| Package | Version | Brings Vulnerable Dependencies | Project |
|---------|---------|-------------------------------|---------|
| `Microsoft.AspNetCore.Authentication.JwtBearer` | 3.1.0 | Moderate vulnerability [GHSA-q7cg-43mg-qp69](https://github.com/advisories/GHSA-q7cg-43mg-qp69) | VulnerableWebApi |
| `Microsoft.Extensions.Logging.Console` | 3.1.0 | Various transitive vulnerabilities | VulnerableConsole |

## Central Package Management

This solution uses Central Package Management (CPM) configured in `Directory.Packages.props`:

- **Centralized version control**: All package versions are defined in one place
- **Consistent versioning**: Ensures all projects use the same package versions
- **Simplified maintenance**: Easy to update package versions across all projects

## Building and Running

### Prerequisites
- .NET 8 SDK or later

### Build the Solution
```bash
dotnet restore
dotnet build
```

### Run Individual Projects

**Console Application:**
```bash
dotnet run --project src/VulnerableConsole
```

**Web API:**
```bash
dotnet run --project src/VulnerableWebApi
```
Then navigate to `https://localhost:5001/swagger` to see the API documentation.

## Security Warnings

When you build or restore this solution, you'll see security warnings like:

```
warning NU1902: Package 'Microsoft.Data.SqlClient' 1.0.19239.1 has a known moderate severity vulnerability
warning NU1903: Package 'Newtonsoft.Json' 10.0.1 has a known high severity vulnerability
```

These warnings are **intentional** and demonstrate how .NET's built-in security scanning works.

## Educational Use Cases

This sample is useful for:

1. **Security Training**: Understanding how vulnerable dependencies affect applications
2. **Tool Testing**: Testing dependency scanning tools and security scanners
3. **DevOps Pipeline Testing**: Verifying that CI/CD pipelines properly detect and handle vulnerable dependencies
4. **Remediation Practice**: Learning how to identify and fix vulnerable dependencies

## Fixing Vulnerabilities

To fix the vulnerabilities in this sample:

1. Update package versions in `Directory.Packages.props` to latest stable versions
2. Remove or replace packages that don't have secure versions available
3. Use `dotnet list package --vulnerable` to identify vulnerable packages
4. Use `dotnet list package --outdated` to find packages that can be updated

## ⚠️ Warning

**This repository contains intentionally vulnerable dependencies and should not be used in production environments.** It is designed for educational and testing purposes only.

## Sample Code Features

- **VulnerableWebApi**: JWT authentication and JSON serialization using vulnerable packages
- **VulnerableLibrary**: Logging and JWT token processing with security issues
- **VulnerableConsole**: Database connectivity and logging with known vulnerabilities
41 changes: 41 additions & 0 deletions VulnerableDependencies.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{34C94C4A-DE9C-4CD9-AD80-F66C69412824}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VulnerableWebApi", "src\VulnerableWebApi\VulnerableWebApi.csproj", "{E55C3A72-CCBE-4C4C-8012-7D2A63A9BB49}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VulnerableLibrary", "src\VulnerableLibrary\VulnerableLibrary.csproj", "{95447720-38D1-4454-A425-B0BF2C45E43C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VulnerableConsole", "src\VulnerableConsole\VulnerableConsole.csproj", "{9E019C7B-FC5C-4666-8A1D-81908068EE22}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{E55C3A72-CCBE-4C4C-8012-7D2A63A9BB49}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E55C3A72-CCBE-4C4C-8012-7D2A63A9BB49}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E55C3A72-CCBE-4C4C-8012-7D2A63A9BB49}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E55C3A72-CCBE-4C4C-8012-7D2A63A9BB49}.Release|Any CPU.Build.0 = Release|Any CPU
{95447720-38D1-4454-A425-B0BF2C45E43C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{95447720-38D1-4454-A425-B0BF2C45E43C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{95447720-38D1-4454-A425-B0BF2C45E43C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{95447720-38D1-4454-A425-B0BF2C45E43C}.Release|Any CPU.Build.0 = Release|Any CPU
{9E019C7B-FC5C-4666-8A1D-81908068EE22}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9E019C7B-FC5C-4666-8A1D-81908068EE22}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9E019C7B-FC5C-4666-8A1D-81908068EE22}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9E019C7B-FC5C-4666-8A1D-81908068EE22}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{E55C3A72-CCBE-4C4C-8012-7D2A63A9BB49} = {34C94C4A-DE9C-4CD9-AD80-F66C69412824}
{95447720-38D1-4454-A425-B0BF2C45E43C} = {34C94C4A-DE9C-4CD9-AD80-F66C69412824}
{9E019C7B-FC5C-4666-8A1D-81908068EE22} = {34C94C4A-DE9C-4CD9-AD80-F66C69412824}
EndGlobalSection
EndGlobal
46 changes: 46 additions & 0 deletions src/VulnerableConsole/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Logging;

// Create logger using vulnerable Microsoft.Extensions.Logging.Console 3.1.0
using var loggerFactory = LoggerFactory.Create(builder =>
builder.AddConsole());
var logger = loggerFactory.CreateLogger<Program>();

logger.LogInformation("Starting Vulnerable Dependencies Console Sample");

// Example 1: Demonstrate vulnerable Microsoft.Data.SqlClient usage
await DemonstrateVulnerableSqlClient(logger);

// Example 2: Demonstrate vulnerable transitive dependencies through logging
DemonstrateVulnerableLogging(logger);

logger.LogInformation("Sample completed");

static async Task DemonstrateVulnerableSqlClient(ILogger logger)
{
try
{
// This uses Microsoft.Data.SqlClient 1.0.19239.1 which has known vulnerabilities
var connectionString = "Server=localhost;Database=TestDb;Integrated Security=true;TrustServerCertificate=true;";

// Note: This will fail to connect since there's no SQL Server, but demonstrates the usage
using var connection = new SqlConnection(connectionString);
logger.LogInformation("Attempting to connect using vulnerable SqlClient...");

// In a real scenario, this would attempt to connect
logger.LogWarning("SqlClient connection attempt (will fail - no server available)");
}
catch (Exception ex)
{
logger.LogError(ex, "Expected error - demonstrating vulnerable SqlClient usage");
}
}

static void DemonstrateVulnerableLogging(ILogger logger)
{
// This logging infrastructure uses vulnerable transitive dependencies
logger.LogDebug("Debug message using vulnerable logging infrastructure");
logger.LogInformation("Information message demonstrating vulnerable transitive dependencies");
logger.LogWarning("Warning about using outdated logging packages");
logger.LogError("Error message showing security risks in dependency chain");
}
18 changes: 18 additions & 0 deletions src/VulnerableConsole/VulnerableConsole.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<!-- Vulnerable direct dependency -->
<PackageReference Include="Microsoft.Data.SqlClient" />

<!-- Package with vulnerable transitive dependencies -->
<PackageReference Include="Microsoft.Extensions.Logging.Console" />
</ItemGroup>

</Project>
42 changes: 42 additions & 0 deletions src/VulnerableLibrary/Class1.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using NLog;
using System.IdentityModel.Tokens.Jwt;

namespace VulnerableLibrary;

/// <summary>
/// Sample library demonstrating usage of vulnerable dependencies
/// </summary>
public class VulnerableLibraryService
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

/// <summary>
/// Demonstrates usage of vulnerable NLog 4.4.0
/// </summary>
public void LogMessage(string message)
{
// This uses vulnerable NLog 4.4.0 which has known security issues
Logger.Info($"Processing message: {message}");
}

/// <summary>
/// Demonstrates usage of vulnerable System.IdentityModel.Tokens.Jwt 5.1.0
/// </summary>
public string ProcessJwtToken(string token)
{
try
{
// This uses vulnerable JWT library 5.1.0 with known security vulnerabilities
var handler = new JwtSecurityTokenHandler();
var jsonToken = handler.ReadJwtToken(token);

Logger.Info($"JWT processed successfully. Subject: {jsonToken.Subject}");
return jsonToken.Subject ?? "Unknown";
}
catch (Exception ex)
{
Logger.Error(ex, "Failed to process JWT token");
throw;
}
}
}
16 changes: 16 additions & 0 deletions src/VulnerableLibrary/NLog.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

<targets>
<target xsi:type="Console" name="console"
layout="${longdate} ${level:uppercase=true} ${logger} ${message} ${exception:format=tostring}" />
<target xsi:type="File" name="file"
fileName="logs/vulnerableapp-${shortdate}.log"
layout="${longdate} ${level:uppercase=true} ${logger} ${message} ${exception:format=tostring}" />
</targets>

<rules>
<logger name="*" minlevel="Debug" writeTo="console,file" />
</rules>
</nlog>
15 changes: 15 additions & 0 deletions src/VulnerableLibrary/VulnerableLibrary.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<!-- Vulnerable direct dependencies -->
<PackageReference Include="NLog" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" />
</ItemGroup>

</Project>
63 changes: 63 additions & 0 deletions src/VulnerableWebApi/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
using Newtonsoft.Json;
using Microsoft.AspNetCore.Authentication.JwtBearer;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// Example usage of vulnerable JWT Bearer authentication
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthentication();

var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();
return forecast;
})
.WithName("GetWeatherForecast")
.WithOpenApi();

// Example endpoint using vulnerable Newtonsoft.Json
app.MapPost("/vulnerable-json", (object data) =>
{
// This demonstrates usage of vulnerable Newtonsoft.Json 10.0.1
var json = JsonConvert.SerializeObject(data);
var deserialized = JsonConvert.DeserializeObject(json);
return Results.Ok(new { original = data, serialized = json, deserialized });
})
.WithName("VulnerableJsonHandling")
.WithOpenApi();

app.Run();

record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
Loading