Skip to content

Commit

Permalink
Fix sql injection in OrderBy
Browse files Browse the repository at this point in the history
  • Loading branch information
Michael Geramb committed Jan 17, 2020
1 parent 66f2deb commit e68a2a1
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 1 deletion.
40 changes: 40 additions & 0 deletions DCCS.Data.Source.Tests/ResultTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -96,5 +96,45 @@ public void Should_bootstrap_from_provided_data()
Assert.AreEqual(sut.Page, ps.Page);
Assert.AreEqual(sut.Total, 99);
}


[Test]
public void Should_order_data()
{
var data = new List<Dummy>();
data.Add(new Dummy { Name = "2" });
data.Add(new Dummy { Name = "1" });
data.Add(new Dummy { Name = "7" });
var ps = new Params { OrderBy = "name" };
var sut = new Result<Dummy>(ps, data.AsQueryable());
var sorted = sut.Data.ToArray();

Assert.AreEqual("1", sorted[0].Name);
Assert.AreEqual("2", sorted[1].Name);
Assert.AreEqual("7", sorted[2].Name);

}


[Test]
public void Should_fail_for_invalid_order()
{
var data = new List<Dummy>();
data.Add(new Dummy { Name = "2" });
data.Add(new Dummy { Name = "1" });
data.Add(new Dummy { Name = "7" });
var ps = new Params { OrderBy = "name'" };
try
{
var sut = new Result<Dummy>(ps, data.AsQueryable());
var sorted = sut.Data.ToArray();
Assert.Fail("Exception not thrown");
}
catch (ArgumentOutOfRangeException)
{

}

}
}
}
19 changes: 18 additions & 1 deletion DCCS.Data.Source/ResultWithoutTotal.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Reflection;

namespace DCCS.Data.Source
{
Expand Down Expand Up @@ -54,6 +55,11 @@ protected IQueryable<T> Sort(IQueryable<T> data)
// Sortieren...
if (!string.IsNullOrWhiteSpace(OrderBy))
{
var members = typeof(T).GetMember(OrderBy, BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance);
if (!members.Any(m => m is FieldInfo || m is PropertyInfo))
{
throw new ArgumentOutOfRangeException(nameof(OrderBy), OrderBy, $"Order by with '{OrderBy}' is not allowed");
}
return data.OrderBy($"{OrderBy} {(Desc ? "desc" : "")}");
}
else if (data.Expression.Type != typeof(IOrderedQueryable<T>))
Expand Down Expand Up @@ -98,7 +104,18 @@ protected IQueryable<T> Paging(IQueryable<T> data)
tempresult = data.Take(Count.Value);
}
}

else
{
Page = 1;
if (Count.HasValue)
{
tempresult = data.Take(Count.Value);
}
else
{
tempresult = data;
}
}
return (tempresult ?? new List<T>().AsQueryable());

}
Expand Down

0 comments on commit e68a2a1

Please sign in to comment.