2

I’ve started to work with security of a website and my task is to prevent XSS attack. I’ve seen the OWASP rules to deal with it. However, I am not sure about which of these rules I should use on my specific case. I have the following .jsp file:

<% // Get Requests InputData data = new InputData(request); int idBcomp = data.getInt("bcomp"); Bcomp bcomp = new Bcomp(); BcompDao bcompDao = new BcompDaoImpl(); bcomp.setId(idBcomp); JSONObject json = new JSONObject(); try { for (Bcomp s : bcompDao.find(bcomp)) { json.accumulate("id", s.getId()); json.accumulate("nome", s.getNome()); json.accumulate("nox", s.getNox()); } } catch (SQLException e) { json.accumulate("erro", e.getMessage()); } catch (Exception e) { json.accumulate("erro", e.getMessage()); } out.write(json.toString()); %> 

I also have the .js file that receives and manipulates the JSON created by the file above. In this file I have the following code:

function import(idBcomp) { $.ajax({ url: 'ajax/bcomp.jsp', data: {bcomp: idBcomp} }).done(function (r) { var obj = $.parseJSON(r); $("#nome").val(obj.nome); $("#nox").val(obj.nox); $("#id_bcomp").val(obj.id); }); } 

Therefore, my question is: Should I use javascript encode, JSON encode or both? And where should I do the encoding? I am using OWASP XSS API for encodeForJavaScript and JSON encoding

2
  • you realize that json IS javascript? (J)ava(S)cript (O)bject (N)otation. It's just a slightly more strict notation, but valid json IS valid javascript. Commented Oct 6, 2015 at 19:48
  • 1
    All JSON is JavaScript, but not all JavaScript is JSON. application/json indicates data only, where application/javascript could be executed. In a security context, it's not good practice to identify data as an executable source. Commented Oct 6, 2015 at 19:50

1 Answer 1

1

JSON encoding. JSON indicates to the browser that the content is DATA ONLY and should not be executed. JavaScript encoding indicates a potentially executable bundle.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, Paul. However, I still have a question. In this code, the data that is used to create the JSON is an untrusted data. Should I encode these data ? If yes, which encoding should I use ? Or do I just need to add the application/json header? In which specific part of the code is it vulnerable ?
Just regular old JSON encoding. Your decoder should not try to execute the data as it is transformed into JavaScript values. If it does, your decoder is woefully broken. Then it is only vulnerable once the data are added to the DOM, and you should most definitely take precaution to scrub the data, but that is between you and how you use the data. You should not be relying on the encoding to manage that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.