How do I prevent a RESTful service from XSS attacks - validation

Of course, I know that the script code is executed on client side. But what countermeasures should be introduced at serice side in order to provide a maximum of security concerning XSS.
Is output encoding reasonable, or are there any other countermeasures that should be applied?
[EDIT]
If I send back the content as HTML encoded, all existing XML schema files and the bean validation will be inoperative since the XSD schema as well the bean validation are using the same regular expression.
<xs:simpleType name="addressNumber">
<xs:restriction base="xs:string">
<xs:pattern value="[0-9]{1}[0-9a-z/\\ -]{0,7}" />
</xs:restriction>
</xs:simpleType>

Finally, I got the answer here on IT - Security! The most important things are:
Use a standart XML parser library that encodes characters like < and >
Check that the content-type header is set to application/xml
Add additional X-Content-Type-Options header and set the value to nosniff
Perform service side input validation (White listing is the most reliable approach)

Related

Proxy to validate xml with xsd

I've been searching for a while for something that can act as a proxy that I can feed it XSDs to validate xml content within the request body of HTTP traffic.
Does anyone know if such a thing exists on Windows or Linux?
I checked out ModSecurity but I am bit lost on it - I believe SecRule XML maybe able to do it but I can't find how I would go about checking the xml against multiple xsd files to see if it passed any particular one?
validateSchema
Description: This operator requires the request body to be processed as XML.
Example:
SecDefaultAction log,deny,status:403,phase:2
SecRule REQUEST_HEADERS:Content-Type ^text/xml$ \
phase:1,t:lowercase,nolog,pass,ctl:requestBodyProcessor=XML
SecRule REQBODY_PROCESSOR "!^XML$" nolog,pass,skip:1
SecRule XML "#validateSchema /path/to/apache2/conf/xml.xsd"
This operator requires request body to be processed as XML.
https://github.com/SpiderLabs/ModSecurity/wiki/Reference-Manual-(v2.x)#validateSchema
I am thinking there is some way of creating Chained rule evaluation and it allows messages through IF any of the rules are met but denies the message through when none are met.
Thank you!
XML / XSD checking in ModSecurity works, but it's not used by a lot of people (unlike the core functionality of ModSec), so I would not be surprised if you found rough edges.
So use with caution and think about alternatives (-> mod_lua, use XML library, etc.).
What stops you from checking them
SecRule XML "#validateSchema /path/to/apache2/conf/xml.xsd" "phase:2,id:1,log,deny"
SecRule XML "#validateSchema /path/to/apache2/conf/xml2.xsd" "phase:2,id:2,log,deny"
If done this way, you can also branch and skip rules depending on the context. Like Header-X, then pass via id:1, if Header-Not-X, then pass via id:2.
If you lack the ModSecurity knowledge to pull this off, then you might want to buy the ModSec Handbook or look at the tutorials at https://netnea.com.

Is it possible to overwrite the value of the message header id in spring integration?

I am using the claim check pattern from spring-integration, but I would like to have the message stored with a custom ID. This should be easy, as the message store implementations are using the incoming message header id to store the message. Is it possible to overwrite the value of the message header id using a header enricher or/and a header filter?
Message header id and the message store
The SimpleMessageStore, as well as the JdbcMessageStore, are using the incoming message ID to store the message. In the addMessage method (the example is from the SimpleMessageStore) we have:
this.idToMessage.put(message.getHeaders().getId(), message);
To have a custom ID it should be enough to have a header enricher before claim check in, where the value of the id header is replaced with a custom value. For example:
<int:header-enricher input-channel="gateDocCheckInReqChannel"
output-channel="gateDocCheckInEnrichedChannel">
<int:header name="id" expression="payload.getDocumentID()" overwrite="true" />
</int:header-enricher>
<int:claim-check-in input-channel="gateDocCheckInEnrichedChannel"
output-channel="gateDocCheckInReplyChannel" message-store="messageStore" />
It does not work; the message header id is not overwritten. I tried having a header filter on ID before the header enricher, but it does not work either.
Related
I found this old post on removing the headers fields that is undone by some internal logic:
http://forum.spring.io/forum/spring-projects/integration/74099-remove-header-fields
Also, there is this closed issue INT-923 on a message handler that undoes header removals.
https://jira.spring.io/browse/INT-923
It is supposed that issue INT-1135 on header filters fixes this behavior.
https://jira.spring.io/browse/INT-1135
Actually the ID and TIMESTAMP header are read-only (MessageHeaderAccessor):
protected boolean isReadOnly(String headerName) {
return (MessageHeaders.ID.equals(headerName) || MessageHeaders.TIMESTAMP.equals(headerName));
}
They are specified for the concrete Message, which is immutable.
Those header are designed for the internal usage in the framework and they can't be changed.
For such a use-case like yours, there is need to introduce addition businessKey and get deal with that not thinking about those interlan headers.
Since you say that you want to determine somehow a message by the ID from the store after claim-ckeck, I suggest you to consder to use MetadataStore to keep ID <-> businessKey pairs to have an ability to restore them in the future somehow.
Of course, you can try to use MutableMessageBuilder for your specific use-case:
MutableMessageBuilder.fromMessage(message)
.setHeader(MessageHeaders.ID, UUID.randomUUID())
.build()
But ID must be UUID anyway.
And right: HeaderFilter doesn't remove those read-only headers as well.
I have overridden the http_requestMethod by doing as like below. The request coming is Post which I have removed from Headers and added PUT.
<int:header-filter input-channel="headerFilterChannel"
header-names="http_requestMethod" output-channel="closeAndCloneOldTasksHeaderEnricherChannel" />
<int:header-enricher input-channel="closeAndCloneOldTasksHeaderEnricherChannel"
output-channel="caresToSfdc">
<int:header name="http_requestMethod" value="PUT" />
</int:header-enricher>
***Before Overriding Log***
GenericMessage [payload=com.cardinalhealth.chh.exception.model.GenericResponse#1948829c, headers={http_requestMethod=POST, replyChannel=org.springframework.messag
**After Overriding Log :**
GenericResponse#142cd5fd, headers={replyChannel=org.springframework.messaging.core.GenericMessagingTemplate$TemporaryReplyChannel#5710c249, http_requestMethod=PUT,

validateRequest=true and requestValidationMode="4.0" lets html through

I have a Web Forms website on IIS7 and .NET 4.5.1 and I want the http requests to be validated using Microsoft's Request validation. The web.config default values for validateRequest and requestValidationMode are supposed to be "true" and "4.0" respectively and that should be what I want (I tried specifying them just in case).
<pages validateRequest="true">
<httpRuntime requestValidationMode="4.0" />
For some reason, when I input an html tag (tried < script > and < a >) in a form then submitting it, I get the expected Potentially Dangerous request error, but the tag gets saved in the database. Why did it go through? I simply take the textbox's Text value as is and send it to my DB, but I expect the error to stop that from happening.
When I tried setting:
<httpRuntime requestValidationMode="2.0" />
The error was the same, but this time, the tag didn't end up in the database, which is what I want.
I would like to understand why the lesser safe validation mode "2.0" is the only one that actually prevents the request from going through in my case, which doesn't seem to make much sense. There must be something I'm missing, please let me know if I should provide other information.
I have found a solution to my own problem. It would appear that Microsoft's documentation about requestValidationMode states that all values above "4.0" is interpreted as "4.0", but that isn't true. Reading this interesting page, I have found out there's a "4.5" value that is valid and does exactly what I wanted.

Data URI and a potentially dangerous Request.Path value

I have tried using a Data URI with this CSS property:
background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAA9JREFUeNpiYGBg8AUIMAAAUgBOUWVeTwAAAABJRU5ErkJggg==");
And locally it works fine.
However, when I am debugging the file appears missing in chrome. If I try to navigate to it, I get: A potentially dangerous Request.Path value was detected from the client (:).
So obviously my application considers the URI for this image suspicious.
How do I get it to show?
I tried relaxing the validation using:
<httpRuntime requestPathInvalidCharacters="" requestValidationMode="2.0" />
<pages validateRequest="false"></pages>
Ideally I wouldn't want to relax the rules too much, only enough to get these data URI images loading.
I would bet that the application considers the request suspicious because of the Base-64 encoded URI. Encoding malicious URLs in Base-64 is a common strategy by attackers to get URLs through front end filters that strip and/or escape URLs, and to obscure the request from any humans reading the code. XSS attacks are commonly done by getting one of these URIs stored in a database and served back to other users.
Because of the high risks of XSS these days, I would hesitate to disable the check. If you can, just use a non-encoded URI. If you can't, you should ask yourself why. If you are trying to enhance security by obfuscating the URI, do know that this is very trivial for an attacker to decode. It is not any form of encryption, just a different way to represent data.

Transformation of web.config

I work on a big asp.net entity framework web application with a lot of EDMX (actually 10, later, more than 30). Each EDMX has his own connection string.
When I deploy, my app, I want to change these connection strings. I can replace them with
xdt:Transform="Replace"
But that I need is to replace only a part of the attribut "connectionString".
If my connection string is :
<add name="DemosEntities" connectionString="metadata=res://*/Demos.csdl|res://*/Demos.ssdl|res://*/Demos.msl;provider=Devart.Data.Oracle;provider connection string="User Id=user;Password=password;Home=OraClient11g_home1;Data Source=VDN131DEV15;Persist Security Info=True;ClientId=CLOEE2"" providerName="System.Data.EntityClient" />
I just want to replace VDN131DEV15 with another string on all my connection strings.
Possible with web.config transformation ?
Thank you
There is no Transform operation defined that will allow you to replace a part of the attribute value rather than the whole value.
I think you would need to write a custom build task to apply an xslt to the file in order to do what you want.

Resources