I have been working over the security issue regarding the persistent-XSS attack and i was able to analyze the issue using fortify.
sends unvalidated data to a web browser , which can result in the browser executing malicious code.
Code is in Java.
void output(OutputStream out){
out.write(byteData); //byteData is a data member of the class of type byte[].
}
At line (2) in above snippet i am getting the notification of xss attack.
So how can i validate it?
You have to validate your data before sending it to your OutputStream
void output(OutputStream out) {
// Validate byteData code here
out.write(byteData);
}
Validation means checking if the code abides by the rules that you want to set for it. For example, if you want to send only numbers, you can make sure that your byteData contains only numbers before sending it.
Related
I am building a web app which runs react on the front end and Java/Spring on the back end.
I am using a RESTful API to communicate with my client (client will communicate with an external API too).
I am facing a problem. When a user registers, I want to send an email verification code. My question is about practice.
Is it ok to send an email with a verification code, store the code in the database and then check if the code is correct?
Or is it better to create some static bean which would hold the code for a while and then check if it's correct?
I am not sure which is better in terms of back-end logic.
I appreciate all help.
It's a very common practice to store this in the DB. Just make sure to cleanup the expired tokens once in a while (maybe on timer, maybe when inserting new ones).
You can also store the tokens in an in-memory cache (EhCahe comes to mind) and set the expiration time accordingly, but this way you lose the cache if the application shuts down. Yes, you can make the cache persistent, but why not go the DB route then?
With that said, think about not storing the token anywhere and instead send the link with the email as an URL parameter and a salted hash as an additional parameter. Once the link is clicked, you can check if the hash matches and if it does, the email parameter wasn't tempered with, so you can mark it as validated. Maybe not Pentagon-level secure, but probably enough for email validation and makes everything easier.
In pseudo-code:
public String hash(String email) {
MessageDigest digester = MessageDigest.getInstance("SHA-256");
digester.update(email.getBytes(StandardCharsets.UTF_8)));
digester.update("RanDOmComplCatEdSalt647826583745".getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(digester.digest());
}
String email = "dude#example.com";
sendEmailWithLink("/verify?email=" + email + "&hash=" + hash(email));
On the way in, you just do the exact same thing to calculate and check if the hash matched:
String email = httpRequest.getParameter("email");
String receivedHash = httpRequest.getParameter("hash");
if (hash(email).equals(receivedHash)) {
//the user didn't do anything funny, mark email as valid
}
Or, taking this idea further but with more security, you can generate something like a JWT that contains the email and is properly encrypted.
I´m developing a personal application, using EMV reader and Javax SmartCardIO, I´m trying to get all the plain data from a SmartCard, I've been reading the specification and some tutorials, even reading some questions here but I came up with a problem:
I'm trying to get the size of a record in the SFI in order to iterate all the records with that information.
I've read in some tutorials that I need to send a request with length 0 and the chip is going to answer with an error code and the correct length of the record("6C XX"), however in my cards (Visa and AMEX) is returning another response which translates to the type of card ("VISA ELECTRON and AMERICAN EXPRESS") and I'm not getting the "6c xx" error.
My code so far looks like this:
byte[] commandArr = {(byte)0x00, (byte)0xB2, (byte)0x01, (byte)0x0C, (byte)0x00};
CommandAPDU commandTest = new CommandAPDU(commandArr);
ResponseAPDU test = this.channel.transmit(commandTest);
System.out.println(hexToAscii(bytesToHex(test.getBytes())));
Both cards have the SFI for the first PSE record in 01 (got that with the select PSE command after the 88 tag).
I'm new using this technology and I'm kind of lost right now, any help is welcome.
Thanks!
In addition to Alexander Vaganov's answer -- javax.smartcardio package handles the 61XX and 6CXX cases automatically, unless told not to do so (by sun.security.smartcardio.t0GetResponse and sun.security.smartcardio.t1GetResponse system properties).
Setting this properties to false should result in the expected behavior (i.e. getting the 6CXX status word).
I am not aware of any documentation for this, so have a look into the source code.
To disable the abovementioned automatic handling of 61XX and 6CXX cases add the following arguments to the java command line:
-Dsun.security.smartcardio.t0GetResponse=false -Dsun.security.smartcardio.t1GetResponse=false
Good luck!
When you establish connection with the card in contact mode, you choose one of two transmission protocol T0 or T1. The main function of them is equal - communicate with card, but realisation and interface are different. Cart may support one of these protocols or both. The one of differenes is how to get responce from card. In T0 responce may constit of two parts (commands). When you got SW=61XX where xx length of response you need perform command GetResponce 00C00000XX to "read" response data. In T1 you get all data with SW at once.
In your case it seems using T1, so card return all data without SW=61XX.
Some parts of documentation:
public abstract Card connect(String protocol) throws CardException
The protocol to use ("T=0", "T=1", or "T=CL"), or "*" to connect using any available protocol.
public abstract ResponseAPDU transmit(CommandAPDU command) throws CardException
Implementations should transparently handle artifacts of the transmission protocol. For example, when using the T=0 protocol, the following processing should occur as described in ISO/IEC 7816-4:
if the response APDU has an SW1 of 61, the implementation should issue a GET RESPONSE command using SW2 as the Lefield. This process is repeated as long as an SW1 of 61 is received. The response body of these exchanges is concatenated to form the final response body.
if the response APDU is 6C XX, the implementation should reissue the command using XX as the Le field.
I'm a beginner java user, and beginning streamer on Twitch.tv. I have been working on developing an IRC bot all night that would streamline moderation on my channel (I want to have that level of customization that using a cookie cutter IRC bot can't give).
One thing that is stumbling me is poll creation. I have looked through the Pirc javadocs and there is no command as far as I can see that checks for messages sent by a channel op, which is crucial to keeping trolls from creating polls, and with my limited knowledge I do not know how to grab extra parameters from a message.
What I want is this:
!poll <question> <c1> <c2> <c3> <seconds>
Any help here? I will add you to my thanks screen on my outro for each stream.
From my quick look through the PIRC javadocs, it looks like the method you want is #onMessage(String channel,
String sender,
String login,
String hostname,
String message)
From here, you can get any information required. Now depending on how you're handling incoming messages, all you need to do it search for the command, which in this case is "!poll" which you'll receive from the message string. From there, you can further parse the information, and do what you want with it.
If you haven't been using them already, the javadocs for pirc are location here: http://www.jibble.org/javadocs/pircbot/index.html
As Jdsfighter said, you need to use the onMessage(...) method from the PircBot superclass. This method is called whenever a message is sent to your channel. I kinda assume you have understood this by now, as making the bot react to chat is alpha and omega when making an IRC bot.
When concerned with Moderators (Operators in IRC terms), the Twitch IRC servers behave in a way that isnt completely understood by PircBot, and I have not been successfull with the User.isOp(...) method from the User class. What I've found successfull is to include the following in my Bot class (not the main class):
Set<String> OPs = new HashSet<String>();
protected void onUserMode(String channel, String sourceNick, String sourceLogin, String sourceHostname, String recipient) {
recipient = recipient.split(" ")[2];
OPs.add(recipient);
}
This Method is called whenever you see a line begining with MODE in the console, like this one:
jtv MODE #channel +o moderatorName
Now, you need to make a method that is called whenever the message recieved starts with "!poll", and checks if the sender of the message is in the OPs Set.
Here's an outline for you, to be placed in the onMessage() method
if (message.toLowerCase().startsWith("!poll") {
if (OPs.contains(sender)) {
//TODO Add body
}
}
Now you just have to make some code that catches the rest of the line after "!Poll" and posts a message back to the channel about the different poll options.
You obviously need somewhere to store your alternatives and how many votes they get each, I suggest simply two arrays, one String[] and one int[].
I have the following pesudocode:
public void sendPB(ObjectId userId, Message.Builder mb) {
if (userId is logged in to server) {
set mb.ackId to random chars
lookup socket and send mb.build()
}
else {
forward message to user's server via RMI
}
}
The problem is Message.Builders do not implement Serializable, so you cannot send it directly via RMI.
Is there an easy way to do this?
I've tried building partial PB from the builder and sending that over, but in order to reconstruct it you need to know the type or the Descriptor. Descriptor doesn't implement Serializable either.
Thanks
Any reason you can't call build(), get a Message, and send it across in whatever the correct format is (e.g., toString()). At the other end, you can inflate it back into a Message, and make it back into a builder with toBuilder() if that's required.
You may also just convert the message to binary format and send that.
Maybe I'm misunderstanding -- the whole point of ProtocolBuffers is to get Messages into a wire representation, so there are a number of ways to do that (most of which are either Serializable or trivially wrapped to be.)
I got it working... I had to include a typeID field in the RMI message. Then, I could take the typeID and resolve it to a Message Builder, and then mergeFrom the bytes of the partially built message.
I've been writing a little application that will let people upload & download files to me. I've added a web service to this applciation to provide the upload/download functionality that way but I'm not too sure on how well my implementation is going to cope with large files.
At the moment the definitions of the upload & download methods look like this (written using Apache CXF):
boolean uploadFile(#WebParam(name = "username") String username,
#WebParam(name = "password") String password,
#WebParam(name = "filename") String filename,
#WebParam(name = "fileContents") byte[] fileContents)
throws UploadException, LoginException;
byte[] downloadFile(#WebParam(name = "username") String username,
#WebParam(name = "password") String password,
#WebParam(name = "filename") String filename) throws DownloadException,
LoginException;
So the file gets uploaded and downloaded as a byte array. But if I have a file of some stupid size (e.g. 1GB) surely this will try and put all that information into memory and crash my service.
So my question is - is it possible to return some kind of stream instead? I would imagine this isn't going to be terribly OS independent though. Although I know the theory behind web services, the practical side is something that I still need to pick up a bit of information on.
Cheers for any input,
Lee
Yes, it is possible with Metro. See the Large Attachments example, which looks like it does what you want.
JAX-WS RI provides support for sending and receiving large attachments in a streaming fashion.
Use MTOM and DataHandler in the programming model.
Cast the DataHandler to StreamingDataHandler and use its methods.
Make sure you call StreamingDataHandler.close() and also close the StreamingDataHandler.readOnce() stream.
Enable HTTP chunking on the client-side.
Stephen Denne has a Metro implementation that satisfies your requirement. My answer is provided below after a short explination as to why that is the case.
Most Web Service implementations that are built using HTTP as the message protocol are REST compliant, in that they only allow simple send-receive patterns and nothing more. This greatly improves interoperability, as all the various platforms can understand this simple architecture (for instance a Java web service talking to a .NET web service).
If you want to maintain this you could provide chunking.
boolean uploadFile(String username, String password, String fileName, int currentChunk, int totalChunks, byte[] chunk);
This would require some footwork in cases where you don't get the chunks in the right order (Or you can just require the chunks come in the right order), but it would probably be pretty easy to implement.
When you use a standardized web service the sender and reciever do rely on the integrity of the XML data send from the one to the other. This means that a web service request and answer only are complete when the last tag was sent. Having this in mind, a web service cannot be treated as a stream.
This is logical because standardized web services do rely on the http-protocol. That one is "stateless", will say it works like "open connection ... send request ... receive data ... close request". The connection will be closed at the end, anyway. So something like streaming is not intended to be used here. Or he layers above http (like web services).
So sorry, but as far as I can see there is no possibility for streaming in web services. Even worse: depending on the implementation/configuration of a web service, byte[] - data may be translated to Base64 and not the CDATA-tag and the request might get even more bloated.
P.S.: Yup, as others wrote, "chuinking" is possible. But this is no streaming as such ;-) - anyway, it may help you.
I hate to break it to those of you who think a streaming web service is not possible, but in reality, all http requests are stream based. Every browser doing a GET to a web site is stream based. Every call to a web service is stream based. Yes, all. We don't notice this at the level where we are implementing services or pages because lower levels of the architecture are dealing with this for you - but it is being done.
Have you ever noticed in a browser that sometimes it can take a while to fetch a page - the browser just keeps cranking away showing the hourglass? That is because the browser is waiting on a stream.
Streams are the reason mime/types have to be sent before the actual data - it's all just a byte stream to the browser, it wouldn't be able to identify a photo if you didn't tell it what it was first. It's also why you have to pass the size of a binary before sending - the browser won't be able to tell where the image stops and the page picks up again.
It's all just a stream of bytes to the client. If you want to prove this for yourself, just get a hold of the output stream at any point in the processing of a request and close() it. You will blow up everything. The browser will immediately stop showing the hourglass, and will display a "cannot find" or "connection reset at server" or some other such message.
That a lot of people don't know that all of this stuff is stream based shows just how much stuff has been layered on top of it. Some would say too much stuff - I am one of those.
Good luck and happy development - relax those shoulders!
For WCF I think its possible to define a member on a message as stream and set the binding appropriately - I've seen this work with wcf talking to Java web service.
You need to set the transferMode="StreamedResponse" in the httpTransport configuration and use mtomMessageEncoding (need to use a custom binding section in the config).
I think one limitation is that you can only have a single message body member if you want to stream (which kind of makes sense).
Apache CXF supports sending and receiving streams.
One way to do it is to add a uploadFileChunk(byte[] chunkData, int size, int offset, int totalSize) method (or something like that) that uploads parts of the file and the servers writes it the to disk.
Keep in mind that a web service request basically boils down to a single HTTP POST.
If you look at the output of a .ASMX file in .NET , it shows you exactly what the POST request and response will look like.
Chunking, as mentioned by #Guvante, is going to be the closest thing to what you want.
I suppose you could implement your own web client code to handle the TCP/IP and stream things into your application, but that would be complex to say the least.
I think using a simple servlet for this task would be a much easier approach, or is there any reason you can not use a servlet?
For instance you could use the Commons open source library.
The RMIIO library for Java provides for handing a RemoteInputStream across RMI - we only needed RMI, though you should be able to adapt the code to work over other types of RMI . This may be of help to you - especially if you can have a small application on the user side. The library was developed with the express purpose of being able to limit the size of the data pushed to the server to avoid exactly the type of situation you describe - effectively a DOS attack by filling up ram or disk.
With the RMIIO library, the server side gets to decide how much data it is willing to pull, where with HTTP PUT and POSTs, the client gets to make that decision, including the rate at which it pushes.
Yes, a webservice can do streaming. I created a webservice using Apache Axis2 and MTOM to support rendering PDF documents from XML. Since the resulting files could be quite large, streaming was important because we didn't want to keep it all in memory. Take a look at Oracle's documentation on streaming SOAP attachments.
Alternately, you can do it yourself, and tomcat will create the Chunked headers. This is an example of a spring controller function that streams.
#RequestMapping(value = "/stream")
public void hellostreamer(HttpServletRequest request, HttpServletResponse response) throws CopyStreamException, IOException
{
response.setContentType("text/xml");
OutputStreamWriter writer = new OutputStreamWriter (response.getOutputStream());
writer.write("this is streaming");
writer.close();
}
It's actually not that hard to "handle the TCP/IP and stream things into your application". Try this...
class MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
response.getOutputStream().println("Hello World!");
}
}
And that is all there is to it. You have, in the above code, responded to an HTTP GET request sent from a browser, and returned to that browser the text "Hello World!".
Keep in mind that "Hello World!" is not valid HTML, so you may end up with an error on the browser, but that really is all there is to it.
Good Luck in your development!
Rodney