CTellius541262 (Community Member) asked a question.

I want to fix this issue "CWE-918: Server Side Request Forgery (SSRF)"

This is my piece of code

[HttpGet]

        [Route("attachment/{attachmentName}/{extension}")]

        [SwaggerResponse(200, "Success")]

        [SwaggerResponse(404, "Record Not Found")]

        [SwaggerResponse(401, "The User is not authorized")]

        [SwaggerResponse(400, "BadRequest")]

        [ApiAuthorizationAttribute(Privilege: "MY_SUMMARY_PAGE", Actions: (new [] { "READ","DELETE" }))]

        public async Task<IActionResult> GetAttachmentByName(string attachmentName, string extension)

        {

            _logger.LogDebug("Entering into GetAttachmentByName() in AttachmentController");

            _logger.LogInfo($"attachmentName : {attachmentName}, extension : {extension}");

            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);

            try

            {

                List<string> imageFileFormats = new List<string>{ "png", "jpg", "jpeg", "heic" };

                if(!imageFileFormats.Contains(extension.ToLower()))

                {

                    string responseMessage = (_config["appSettings:" + "ViewAttachmentResponseMessage"]).ToString();

                    _logger.LogDebug("File formats other than image cannot be viewed currently");

                    return BadRequest(responseMessage);

                }

                if(attachmentName == string.Empty || attachmentName == null)

                {

                    _logger.LogError("Attachment Name can't be null");

                    return BadRequest("Attachment Name can't be null");

                }

                if (!Regex.IsMatch(attachmentName, @"^[a-zA-Z0-9_.-]+$"))

                {

                    _logger.LogError("Invalid attachment name format");

                    return BadRequest("Invalid attachment name format");

                }

                string compile_path = "api/attachment/{attachmentName}/{extension}";

                compile_path = compile_path.Replace("{attachmentName}", attachmentName)

                    .Replace("{extension}", extension);

               

                if (!Uri.TryCreate(compile_path, UriKind.RelativeOrAbsolute, out Uri requestUri))

                {

                    _logger.LogError("Invalid attachment URL");

                    return BadRequest("Invalid attachment URL");

                }

                string destinationPath = Path.Join(AppDomain.CurrentDomain.BaseDirectory, "Attachments") ;

                string fileName = attachmentName + "." + extension;

                string fullPath = Path.Join(destinationPath, fileName);

 

                if (!System.IO.File.Exists(fullPath))

                {

                    using (var client = new HttpClient())

                    {

                        string urlValue = Convert.ToString(_config["appSettings:" + "OldUrl"]);

                        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _config["appSettings:" + "OldAppToken"]);

 

                        client.BaseAddress = new Uri(urlValue);

                        var httpresponse = await client.GetAsync(compile_path);

                        if (httpresponse.StatusCode == System.Net.HttpStatusCode.OK)

                        {

                            using (var ms = new MemoryStream(httpresponse.Content.ReadAsByteArrayAsync().Result))

                            {

                                using (var fs = new FileStream(fullPath, FileMode.Create))

                                {

                                    ms.WriteTo(fs);

                                }                                

                            }

                        }

                        else

                        {

                             _logger.LogDebug("Response : Record not found");

                            return NotFound("Record not found");

                        }

                    }

                }

                 var image = System.IO.File.OpenRead(fullPath);

                _logger.LogDebug("Response : " + response);

                return File(image, "image/" +extension);

            }

            catch (Exception exception)

            {

                _logger.LogError(exception.ToString(), "An error occurred while getting GetAttachmentByName in AttachmentController");

                return BadRequest("Error occurred in GetAttachmentByName method");

            }

        }

 

I'm getting this at the line var httpresponse = await client.GetAsync(compile_path);

 

Please provide me with a solution


  • Hi @CTellius541262 (Community Member)​,

     

    The recommendation for mitigating against SSRF flaws is to use strict validation on the untrusted data used to build the requested URL. Typically, Veracode Static Analysis will not automatically detect such conditional logic. If you believe the validation you have done is sufficient, you will need to raise a mitigation for approval by your security team.

     

    Kind regards,

    Duncan

    Expand Post

Topics (4)

No articles found
Loading

Ask the Community

Get answers, share a use case, discuss your favorite features, or get input from the community.