Long story short, no matter what I try VeraCode continues to flag 8 lines of my code as flaws with CWE 918. This is old code so I'm not sure why it's suddenly being flagged.
Here's an example [offending] method with the flagged line in bold
public virtual async Task<HttpResponseMessage> Put(string controller = "", Dictionary<string, object> parameters = null, object body = null)
{
if (string.IsNullOrWhiteSpace(ApiBaseUrl)) return null;
HttpResponseMessage response = null;
using (var client = GetHttpClient())
{
client.BaseAddress = new Uri(ApiBaseUrl);
if (!string.IsNullOrEmpty(Token)) client.DefaultRequestHeaders.Add("Token-Key", Token);
if (!string.IsNullOrEmpty(DeviceId)) client.DefaultRequestHeaders.Add("DeviceId", DeviceId);
var url = GenerateUrl(controller, parameters);
var requestBody = GeneratedHttpContent(body);
if (requestBody == null) requestBody = new StringContent("");
**response = await client.PutAsync(url, requestBody);**
await LogError(response);
return response;
}
}
Here's my proposed fix that utilized an extension method to validate the URL
var url = GenerateUrl(controller, parameters);
var requestBody = GeneratedHttpContent(body);
if (requestBody == null) requestBody = new StringContent("");
**if (url.IsValidUrl())
{
response = await client.PutAsync(url, requestBody);
}
else
{
response = new HttpResponseMessage(HttpStatusCode.BadRequest);
}**
await LogError(response);
return response;
Here is the extension method with a VeraCode attribute
[RedirectUrlCleanser]
public static bool IsValidUrl(this string source)
{
return Uri.TryCreate(source, UriKind.RelativeOrAbsolute, out Uri uriResult) && Uri.IsWellFormedUriString(source, UriKind.RelativeOrAbsolute);
}
I can have VeraCode automatically mitigate based on the attribute, but our client will be performing their own scan and certainly won't have that setting enabled.
Any ideas on how I can resolve this would be appreciated.
The true source of the flaw is inside of your GenerateUrl method which is unfortunately not shown, but here is the general idea of what the Veracode is complaining about.
For CWE ID 918 it is hard to make Veracode recognize your fix unless you have static URL. You need to validate all your inputs that become parts of your request URL.
Below is what I found at the Veracode site:
https://community.veracode.com/s/question/0D52T00004i1UiSSAU/how-to-fix-cwe-918-veracode-flaw-on-webrequest-getresponce-method
The complete solution existed only for the case where you have single or some small number of possible input values (white list):
public WebResponse ProxyImage(string image_host, string image_path)
{
string validated_image_host = AllowedHosts.Host1;
if (image_host.Equals(AllowedHosts.Host2))
validated_image_host = AllowedHosts.Host2;
string validated_image = AllowedImages.Image1;
if (image_path.Equals(AllowedImages.Image2))
validated_image = AllowedImages.Image2;
string url = $"http://{validated_image_host}.example.com/{validated_image}";
return WebRequest.Create(url).GetResponse();
}
If the set of possible valid values is too large for that kind of validation then you need to fix the flaw by implementing dynamic validation of inputs using regular expressions. Unfortunately, Veracode is not smart enough to recognize that kind of fix, so "mitigation by design" is still required.
public WebResponse ProxyImage(string image_host, string image_path)
{
var image_host_regex = new System.Text.RegularExpressions.Regex("^[a-z]{1,10}$");
if (!image_host_regex.Match(image_host).Success)
throw new ArgumentException("Invalid image_host");
var image_path_regex = new System.Text.RegularExpressions.Regex("^/[a-z]{1,10}/[a-z]{1,255}.png$");
if (!image_path_regex.Match(image_path).Success)
throw new ArgumentException("Invalid image_host");
string url = $"http://{image_host}.example.com/{image_path}";
return WebRequest.Create(url).GetResponse();
}
Another way to fix this issue (which is kind of a hack) is to append your query string parameters in the baseAddress of the HttpClient, this way the veracode will not treat it like a flaw.
Here is how the solution would look like
public async Task<Data> GetData(string input)
{
try
{
var httpClient = new HttpClient();
//Appended the parameter in base address to
//to fix veracode flaw issue
httpClient.BaseAddress = new Uri($"https://someurl.com/somefunction/{input}");
//passing empty string in GetStringAsync to make sure
//veracode doesn't treat it like modifying url
var content = await httpClient.GetStringAsync("");
return JsonConvert.DeserializeObject<Data>(content);
}
}
Related
I am very new to the whole consept of API's. So far, I managed to build a web api that has GET,POST,PUT and DELETE methods.
Now, from an ASP.NET project, I try to finally use my web api.
Here's what I do for GET method:
string info = new WebClient() { }.DownloadString("https://mywebapisite.com/item/" + id);
Item item = JsonConvert.DeserializeObject<Item>(info);
This functions all fine. As you can see, all the GET method needs is an id.
However, for the POST method, I have no clue what to do.
I can create a new Item instance, but don't know what to do with it.
By the way, I also used ASP.NET to make my web.api.
There is a built-in feature in ASP.NET 5 called Swagger. It can perform all the tasks very succesfully. Is there like a code-behind for what Swagger does.
PS: I know that this question must be very common and basic. If you could refer me to another question in stackoverflow or simply tell me what to search on google I would appreciate it. (As you may guess, I don't even know what to search for)
pseudo code to consume post request in C#
var requestObj = GetDummyDataTable();
using (var client = new HttpClient())
{
// Setting Base address.
client.BaseAddress = new Uri("https://localhost:8080/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = new HttpResponseMessage();
// HTTP POST
response = await client.PostAsJsonAsync("api/product", requestObj).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
// Reading Response.
string result = response.Content.ReadAsStringAsync().Result;
var responseObj = JsonConvert.DeserializeObject<DataTable>(result);
}
}
You can refer the following code to call the API using HttpClient:
////using System.Net.Http.Headers;
////using System.Text;
using (var client = new HttpClient())
{
var requesturi = "https://localhost:7110/api/ToDo/relativeAddress";
var item = new TestUserViewModel()
{
Name = "John Doe",
Age = 33
};
////using System.Text.Json; // use JsonSerializer.Serialize method to convert the object to Json string.
StringContent content = new StringContent(JsonSerializer.Serialize(item), Encoding.UTF8, "application/json");
//HTTP POST
var postTask = client.PostAsync(requesturi, content);
postTask.Wait();
var result = postTask.Result;
if (result.IsSuccessStatusCode)
{
var Content = await postTask.Result.Content.ReadAsStringAsync();
return RedirectToAction("Privacy");
}
}
The API method like this:
[Route("api/[controller]")]
[ApiController]
public class TodoController : ControllerBase
{
[HttpPost]
[Route("relativeAddress")]
public string GetAddress([FromBody] TestUserViewModel testUser)
{
return "Address A";
}
And the result like this:
You can also refer this link to set the Content-Type.
You seem a little bit lost, and I get it. Api learning path is kinda weird, I recommend you watch a tutorial (My favorite https://www.youtube.com/playlist?list=PLLWMQd6PeGY0bEMxObA6dtYXuJOGfxSPx)
But if you need code asap, you could refer the following code.
Ps: The others answers are really good!
using System.Net.Http;
using System.Net.Http.Headers;
public class ApiHelper
{
public HttpClient ApiClient { get; set; }
public void InitializeClient()
{
ApiClient = new HttpClient();
ApiClient.BaseAddress = new Uri("https://mywebapisite.com/");
ApiClient.DefaultRequestHeaders.Accept.Clear();
ApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task PostSomething(FormUrlEncodedContent data)
{
using (HttpResponseMessage response = await ApiClient.PostAsync("/item",data)
{
var result = await response.Content.ReadAsAsync<string>();
}
}
}
I want to create lets say a master/core api.Want to check for a certain parameter value and redirect to a an external api hosted in the same server.I have an api with uri http://hello.test.com/auth which takes two auth params Username and Password.Now i add a third parameter lets say Area.
{
"Username":"jason",
"Password":"bourne",
"Area":"mars"
}
Now coming to the master api, if with this uri for example http://master.test.com/v1/mster and i pass Username, Password and Area,and if the Area has value of lets say "mars" it should call the external mars api having uri http://mars.test.com/auth ,do the auth the process and return the response in the master api.is this possible?
With my /auth api i have this controller returning the response :
[HttpPost]
[Route(ApiEndpoint.AUTH)]
public HttpResponseMessage Auth(Login authBDTO)
{
if (!ModelState.IsValid)
return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState);
using (AccountBusinessService accountService = new AccountBusinessService())
{
var result = accountService.Auth(authBDTO);
return Request.CreateResponse(HttpStatusCode.OK, result);
}
}
Any Help Appreciated.Couldnt find this exact scenario in here.Sorry if too naive.
Found a workaround.This did the work.
[Route(ApiEndpoint.SAS)]
public IHttpActionResult esp(Login auth)
{
if (auth.Coop == "PMC")
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:60069/api/v1/auth");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
Username = auth.UserName,
Password = auth.Password
});
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(result);
obj.BaseUrl = "http://localhost:60069/api/v1";
return Ok(obj);
}
}
I am having troubles trying to get information back from a Lambda Function in AWS. The Lambda function is behind API Gateway.
If I run the function straight from the Lambda console or from the API, works ok. If I call it with this code returns [].
I am not getting any problems if the token is correct and I can see inside the Lambda function the parameter 'LastUpdate'.
Here is the code:
public async Task<string> GetUpdates(long ticksLastCheck, string token)
{
string Error = "";
string response = "";
object data = new
{
LastUpdate = ticksLastCheck
};
var myContent = JsonConvert.SerializeObject(data);
var buffer = System.Text.Encoding.UTF8.GetBytes(myContent);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
//I have tested without ConfigureAwait and did not work either
var responseSync = await _client.PostAsync("getUpdates", byteContent).ConfigureAwait(false);
if (responseSync != null)
{
//I have tested with await and did not work either. With await ".Result" should be removed from the line below.
var response2 = responseSync.Content.ReadAsStringAsync();
response = response2.Result;
}
return response;
}
If I call it from Postman works as well. Is there any header or parameter that Postman sends and I am missing?
My bad. The field in DynamoDB is a string and I was sending it as a long and never converting to string.
So as soon as I change:
object data = new
{
LastUpdate = ticksLastCheck
};
into this
object data = new
{
LastUpdate = ticksLastCheck.ToString()
};
I am getting the expected response.
Thank you.
I created the Wep API in ASP.Net core to return the PDF. Here is my code:
public HttpResponseMessage Get(int id)
{
var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
var stream = new System.IO.FileStream(#"C:\Users\shoba_eswar\Documents\REquest.pdf", System.IO.FileMode.Open);
response.Content = new StreamContent(stream);
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = "NewTab";
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
return response;
}
But it returns only the JSON response:
{
"version":{
"major":1,
"minor":1,
"build":-1,
"revision":-1,
"majorRevision":-1,
"minorRevision":-1
},
"content":{
"headers":[
{
"key":"Content-Disposition",
"value":[
"attachment; filename=NewTab"
]
},
{
"key":"Content-Type",
"value":[
"application/pdf"
]
}
]
},
"statusCode":200,
"reasonPhrase":"OK",
"headers":[
],
"requestMessage":null,
"isSuccessStatusCode":true
}
Am I doing anything wrong here?
As explained in ASP.NET Core HTTPRequestMessage returns strange JSON message, ASP.NET Core does not support returning an HttpResponseMessage (what package did you install to get access to that type?).
Because of this, the serializer is simply writing all public properties of the HttpResponseMessage to the output, as it would with any other unsupported response type.
To support custom responses, you must return an IActionResult-implementing type. There's plenty of those. In your case, I'd look into the FileStreamResult:
public IActionResult Get(int id)
{
var stream = new FileStream(#"path\to\file", FileMode.Open);
return new FileStreamResult(stream, "application/pdf");
}
Or simply use a PhysicalFileResult, where the stream is handled for you:
public IActionResult Get(int id)
{
return new PhysicalFileResult(#"path\to\file", "application/pdf");
}
Of course all of this can be simplified using helper methods, such as Controller.File():
public IActionResult Get(int id)
{
var stream = new FileStream(#"path\to\file", FileMode.Open);
return File(stream, "application/pdf", "FileDownloadName.ext");
}
This simply abstracts the creation of a FileContentResult or FileStreamResult (for this overload, the latter).
Or if you're converting an older MVC or Web API application and don't want to convert all your code at once, add a reference to WebApiCompatShim (NuGet) and wrap your current code in a ResponseMessageResult:
public IActionResult Get(int id)
{
var response = new HttpResponseMessage(HttpStatusCode.OK);
var stream = ...
response.Content...
return new ResponseMessageResult(response);
}
If you don't want to use return File(fileName, contentType, fileDownloadName), then the FileStreamResult doesn't support setting the content-disposition header from the constructor or through properties.
In that case you'll have to add that response header to the response yourself before returning the file result:
var contentDisposition = new ContentDispositionHeaderValue("attachment");
contentDisposition.SetHttpFileName("foo.txt");
Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
I couldn't comment the answer by CodeCaster since my reputation isn't high enough.
When trying
public IActionResult Get(int id)
{
using (var stream = new FileStream(#"path\to\file", FileMode.Open))
{
return File(stream, "application/pdf", "FileDownloadName.ext");
}
}
we got a
ObjectDisposedException: Cannot access a disposed object. Object name:
'Cannot access a closed file.'. System.IO.FileStream.BeginRead(byte[]
array, int offset, int numBytes, AsyncCallback callback, object state)
We removed the using
[HttpGet]
[Route("getImageFile")]
public IActionResult GetWorkbook()
{
var stream = new FileStream(#"pathToFile", FileMode.Open);
return File(stream, "image/png", "image.png");
}
And that worked. This is ASP.NET Core 2.1 running in IIS Express.
I don't have enough reputation to post this as a comment, so posting as an answer. The first 3 solutions from #CodeCaster and the solution from #BernhardMaertl are correct.
However, for someone who may not work with files often (like me), please note that if the process running this code (e.g. the API) only has read permissions to the file, you will need to specify that as the third parameter when creating your FileStream, otherwise the default behavior is to open the file for read/write and you will get an exception since you do not have write permissions.
The 3rd solution from #CodeCaster would then look like this:
public IActionResult Get(int id)
{
var stream = new FileStream(#"path\to\file", FileMode.Open, FileAccess.Read);
return File(stream, "application/pdf", "FileDownloadName.ext");
}
i am using RestSharp to consume the CapsuleCRM API.
When you POST to create an entity, the API does not return anything in the body of the response, only a location header to the newly created row.
Like so:
http://developer.capsulecrm.com/v1/writing/
HTTP/1.1 201 Created
Location: https://sample.capsulecrm.com/api/party/1000
So, if RestSharp is to be able to return an object, it must follow that location header url, and retrieve the new object from there, but this does not seem to be happening.
This questions is similar to a different question, but not a duplicate:
RestSharp returns null value when response header has location field
Update:
I have posted a hacky solution I came up with as an answer, but is there really no way for RestSharp to handle this by default?
I was able to make this work by making a tweaked version of the
public T Execute<T>(RestRequest request) where T : new()
method, but it really feels like there should be a better solution to this.
Source code at:
https://github.com/bjovas/CapsuleDotNet/blob/master/src/CapsuleDotNetWrapper/CapsuleApi.cs
public T CreateExecute<T>(RestRequest request) where T : new()
{
var client = new RestClient();
client.BaseUrl = BaseUrl;
client.Authenticator = new HttpBasicAuthenticator(_authtoken, "x");
var response = client.Execute<T>(request);
string locationUrl = (string)response.Headers.Where(h => h.Type == ParameterType.HttpHeader && h.Name == "Location").SingleOrDefault().Value;
int id;
if (int.TryParse(locationUrl.Remove(0, string.Format("{0}{1}", client.BaseUrl, request.Resource).Length), out id))
{
var secondRequest = new RestRequest();
secondRequest.Resource = locationUrl.Remove(0, string.Format("{0}", client.BaseUrl).Length);
secondRequest.RootElement = request.RootElement;
return Execute<T>(secondRequest);
}
else
throw new ApplicationException("Could not get ID of newly created row");
}