Ongoing work on automatically generating some error responses

This commit is contained in:
emcho 2010-05-01 21:36:52 +00:00
parent 1d4945e563
commit 29c128ce74
9 changed files with 293 additions and 235 deletions

View File

@ -7,6 +7,7 @@
package org.ice4j;
import org.ice4j.message.*;
import org.ice4j.stack.*;
/**
* The class is used to dispatch incoming stun messages. Apart from the message
@ -26,28 +27,27 @@ public class StunMessageEvent
private static final long serialVersionUID = 41267843L;
/**
* The sending address.
* The message as we got it off the wire.
*/
private final TransportAddress remoteAddress;
private final RawMessage rawMessage;
/**
* Constructs a StunMessageEvent according to the specified message.
* @param sourceAddress the access point that received the message
* @param message the message itself
* @param remoteAddress the address that sent the message
*
* @param rawMessage the crude message we got off the wire.
* @param parsedMessage the message itself
*/
public StunMessageEvent(TransportAddress sourceAddress,
Message message,
TransportAddress remoteAddress)
public StunMessageEvent(RawMessage rawMessage,
Message parsedMessage)
{
super(sourceAddress, message);
this.remoteAddress = remoteAddress;
super(rawMessage.getLocalAddress(), parsedMessage);
this.rawMessage = rawMessage;
}
/**
* Returns a <tt>TransportAddress</tt> referencing the access point where
* the message was received.
*
* @return a descriptor of the access point where the message arrived.
*/
public TransportAddress getLocalAddress()
@ -57,11 +57,12 @@ public class StunMessageEvent
/**
* Returns the address that sent the message.
*
* @return the address that sent the message.
*/
public TransportAddress getRemoteAddress()
{
return remoteAddress;
return rawMessage.getRemoteAddress();
}
/**
@ -82,4 +83,14 @@ public class StunMessageEvent
return buff.toString();
}
/**
* Returns the raw message that caused this event.
*
* @return the {@link RawMessage} that caused this event.
*/
public RawMessage getRawMessage()
{
return rawMessage;
}
}

View File

@ -112,6 +112,13 @@ public abstract class Attribute
*/
public static final char HEADER_LENGTH = 4;
/**
* For attributes that have arriving in incoming messages, this fiels
* contains their original location in the binary array so that we could
* later more easily verify attributes like MESSAGE-INTEGRITY.
*/
private int locationInMessage = -1;
/**
* Creates an empty STUN message attribute.
*
@ -176,6 +183,32 @@ public abstract class Attribute
*/
public abstract byte[] encode();
/**
* For attributes that have arriving in incoming messages, this method
* stores their original location in the binary array so that we could
* later more easily verify attributes like MESSAGE-INTEGRITY.
*
* @param index the original location of this attribute in the datagram
* we got off the wire
*/
public void setLocationInMessage(int index)
{
this.locationInMessage = index;
}
/**
* For attributes that have arriving in incoming messages, this method
* returns their original location in the binary array so that we could
* later more easily verify attributes like MESSAGE-INTEGRITY.
*
* @return the original location of this attribute in the datagram
* we got off the wire or -1 if this is not an incoming {@link Attribute}
*/
public int getLocationInMessage()
{
return this.locationInMessage;
}
/**
* Sets this attribute's fields according to attributeValue array.
*

View File

@ -122,6 +122,7 @@ public class AttributeDecoder
}
decodedAttribute.setAttributeType(attributeType);
decodedAttribute.setLocationInMessage(offset);
decodedAttribute.decodeAttributeBody(bytes,
(char)(Attribute.HEADER_LENGTH + offset), attributeLength);

View File

@ -687,6 +687,9 @@ public abstract class Message
Attribute att = AttributeDecoder.decode(
binMessage, offset, (char)(length - offset));
performAttributeSpecificActions(att, binMessage,
originalOffset, offset);
message.addAttribute(att);
offset += att.getDataLength() + Attribute.HEADER_LENGTH;
}
@ -694,6 +697,191 @@ public abstract class Message
return message;
}
/**
* Executes actions related specific attributes like asserting proper
* fingerprint checksum.
*
* @param attribute the <tt>Attribute</tt> we'd like to process.
* @param binMessage the byte array that the message arrived with.
* @param offset the index where data starts in <tt>binMessage</tt>.
* @param msgLen the number of message bytes in <tt>binMessage</tt>.
*
* @throws StunException if there's something in the
* <tt>attribute</tt> that caused us to discard the whole message (e.g. an
* invalid checksum
* or username)
*/
private static void performAttributeSpecificActions(Attribute attribute,
byte[] binMessage,
int offset,
int msgLen)
throws StunException
{
//check finger print CRC
if (attribute instanceof FingerprintAttribute)
{
if (!validateFingerprint((FingerprintAttribute)attribute,
binMessage, offset, msgLen))
{
//RFC 5389 says that we should ignore bad CRCs rather than
//reply with an error response.
throw new StunException("Wrong value in FINGERPRINT");
}
}
}
/**
* Recalculates the FINGERPRINT CRC32 checksum of the <tt>message</tt>
* array so that we could compare it with the value brought by the
* {@link FingerprintAttribute}.
*
* @param fingerprint the attribute that we need to validate.
* @param message the message whose CRC32 checksum we'd need to recalculate.
* @param offset the index in <tt>message</tt> where data starts.
* @param length the number of bytes in <tt>message</tt> that the CRC32
* would need to be calculated over.
*
* @return <tt>true</tt> if <tt>FINGERPRINT</tt> contains a valid CRC32
* value and <tt>false</tt> otherwise.
*/
private static boolean validateFingerprint(FingerprintAttribute fingerprint,
byte[] message,
int offset,
int length)
{
byte[] incomingCrcBytes = fingerprint.getChecksum();
//now check whether the CRC really is what it's supposed to be.
//re calculate the check sum
byte[] realCrcBytes = FingerprintAttribute.calculateXorCRC32(
message, offset, length);
//CRC validation.
if ( ! Arrays.equals(incomingCrcBytes, realCrcBytes))
{
if (logger.isLoggable(Level.FINE))
{
logger.fine(
"An incoming message arrived with a wrong FINGERPRINT "
+"attribute value. "
+"CRC Was:" + Arrays.toString(incomingCrcBytes)
+ ". Should have been:" + Arrays.toString(realCrcBytes)
+". Will ignore.");
}
return false;
}
return true;
}
/**
* Recalculates the HMAC-SHA1 signature of the <tt>message</tt> array so
* that we could compare it with the value brought by the
* {@link MessageIntegrityAttribute}.
*
* @param msgInt the attribute that we need to validate.
* @param message the message whose SHA1 checksum we'd need to recalculate.
* @param offset the index in <tt>message</tt> where data starts.
* @param length the number of bytes in <tt>message</tt> that the SHA1 would
* need to be calculated over.
*
* @return <tt>true</tt> if <tt>msgInt</tt> contains a valid SHA1 value and
* <tt>false</tt> otherwise.
*/
private boolean validateMessageIntegrity(MessageIntegrityAttribute msgInt,
byte[] message,
int offset,
int length)
{
//first get a password for the username specified with this message.
UsernameAttribute unameAttr
= (UsernameAttribute)getAttribute(Attribute.USERNAME);
if (unameAttr == null)
{
logger.info( "Received a message containing a "
+" MESSAGE-INTEGRITY attribute and no USERNAME");
return false;
}
String username = new String(unameAttr.getUsername());
int colon = username.indexOf(":");
if( username.length() < 1
|| colon < 1)
{
if(logger.isLoggable(Level.FINE))
{
logger.log(Level.FINE, "Received a message with an improperly "
+"formatted username");
}
return false;
}
String lfrag = username.substring(0, colon);
byte[] key = StunStack.getInstance()
.getCredentialsManager().getLocalKey(lfrag);
if(key == null)
return false;
//now check whether the SHA1 matches.
byte[] expectedSha1 = MessageIntegrityAttribute
.calculateHmacSha1(message, offset, length, key);
if (!Arrays.equals(expectedSha1, msgInt.getHmacSha1Content()))
{
if(logger.isLoggable(Level.FINE))
{
logger.log(Level.FINE, "Received a message with a wrong "
+"MESSAGE-INTEGRITY HMAC-SHA1 signature");
}
return false;
}
if (logger.isLoggable(Level.FINEST))
logger.finest("Successfully verified msg integrity");
return true;
}
/**
* Asserts the validity of the user name we've received in
* <tt>unameAttr</tt>.
*
* @param unameAttr the attribute that we need to validate.
*
* @return <tt>true</tt> if <tt>unameAttr</tt> contains a valid user name
* and <tt>false</tt> otherwise.
*/
private static boolean validateUsername(UsernameAttribute unameAttr)
{
String username = new String(unameAttr.getUsername());
int colon = username.indexOf(":");
if( username.length() < 1
|| colon < 1)
{
if(logger.isLoggable(Level.FINE))
{
logger.log(Level.FINE, "Received a message with an improperly "
+"formatted username");
}
return false;
}
String lfrag = username.substring(0, colon);
return StunStack.getInstance()
.getCredentialsManager().checkLocalUserName(lfrag);
}
/**
* Verify that the message has all obligatory attributes and throw an
* exception if this is not the case.

View File

@ -1,148 +0,0 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package org.ice4j.message;
import org.ice4j.attribute.*;
/**
* The {@link MessageDecodeException} is thrown during decoding in order
* to indicate what problems there might have been with a particular incoming
* message. The exception is particularly useful when decoding incoming requests
* so that the stack could generate an appropriate error response.
*
* @author Emil Ivov
*/
public class MessageDecodeException
extends Exception
{
/**
* Dummy version UID
*/
static final long serialVersionUID = -1L;
/**
* The error code to use in case we do not want this exception to cause a
* response and would prefer to discard instead.
*/
public static int NO_RESPONSE = -1;
/**
* A STUN Error Response code to use if the message that caused the
* exception was a {@link Request} and we could send an error response.
*/
private int stunResponseCode = NO_RESPONSE;
/**
* An attribute to include in the error response.
*/
private Attribute responseAttribute = null;
/**
* The ID of the transaction to use in case the exception allows for
* sending an error response.
*/
private byte[] transactionID = null;
/**
* Creates a new <tt>MessageDecodeException</tt> instance.
*
* @param message a text message explaining the exception
*/
public MessageDecodeException(String message)
{
super(message);
}
/**
* Creates a new <tt>MessageDecodeException</tt> instance.
*
* @param message a text message explaining the exception
* @param cause A reference to a {@link Throwable} instance in case this
* exception was caused by another, unexpected exception.
*/
public MessageDecodeException(String message,
Throwable cause)
{
super(message, cause);
}
/**
* Creates a new <tt>MessageDecodeException</tt> instance.
*
* @param message a text message explaining the exception
* @param stunResponseCode a STUN Error Response code to use if the message
* that caused the exception was a {@link Request} and we could send an
* error response, or <tt>-1</tt> in case we should not reply.
* @param transactionID the id of the transaction to use in an error
* response.
*/
public MessageDecodeException(String message,
int stunResponseCode,
byte[] transactionID)
{
super(message);
this.stunResponseCode = stunResponseCode;
this.transactionID = transactionID;
}
/**
* Creates a new <tt>MessageDecodeException</tt> instance.
*
* @param message a text message explaining the exception
* @param stunResponseCode a STUN Error Response code to use if the message
* that caused the exception was a {@link Request} and we could send an
* error response, or <tt>-1</tt> in case we should not reply.
* @param transactionID the id of the transaction to use in an error
* response.
* @param attribute the Attribute an attribute to include in the error
* response.
*/
public MessageDecodeException(String message,
int stunResponseCode,
byte[] transactionID,
Attribute attribute)
{
super(message);
this.stunResponseCode = stunResponseCode;
this.transactionID = transactionID;
}
/**
* Returns a STUN Error Response code to use if the message that caused the
* exception was a {@link Request} and we could send an error response.
*
* @return a STUN Error Response code to use if the message that caused the
* exception was a {@link Request} and we could send an error response.
*/
public int getErrorResponseCode()
{
return stunResponseCode;
}
/**
* Returns whatever attribute would have to be included in a potential
* error response like for example the attribute that cause a 420 error.
*
* @return whatever attribute would have to be included in a potential
* error response like for example the attribute that cause a 420 error.
*/
public Attribute getResponseAttribute()
{
return responseAttribute;
}
/**
* Returns the id of the transaction to use in an error response.
*
* @return the id of the transaction to use in an error response.
*/
public byte[] getTransactionID()
{
return transactionID;
}
}

View File

@ -126,7 +126,7 @@ class MessageProcessor
(char) 0,
(char) rawMessage.getMessageLength());
}
catch (MessageDecodeException ex)
catch (StunException ex)
{
errorHandler.handleError("Failed to decode a stun mesage!",
ex);
@ -137,10 +137,7 @@ class MessageProcessor
logger.finest("Dispatching a StunMessageEvent.");
StunMessageEvent stunMessageEvent =
new StunMessageEvent(
rawMessage.getLocalAddress(),
stunMessage,
rawMessage.getRemoteAddress());
new StunMessageEvent(rawMessage, stunMessage);
messageHandler.handleMessageEvent(stunMessageEvent);
}

View File

@ -15,7 +15,7 @@ import org.ice4j.*;
*
* @author Emil Ivov
*/
class RawMessage
public class RawMessage
{
/**
* The message itself.

View File

@ -16,6 +16,8 @@ import org.ice4j.attribute.*;
import org.ice4j.message.*;
import org.ice4j.security.*;
import com.sun.corba.se.impl.protocol.*;
/**
* The entry point to the Stun4J stack. The class is used to start, stop and
* configure the stack.
@ -524,6 +526,7 @@ public class StunStack
}
//validate attributes that need validation.
validateRequestAttributes((Request)msg, event.getRawMessage());
eventDispatcher.fireMessageEvent(event);
@ -591,73 +594,57 @@ public class StunStack
* Executes actions related specific attributes like asserting proper
* checksums or verifying the validity of user names.
*
* @param attribute the <tt>Attribute</tt> we'd like to process.
* @param binMessage the byte array that the message arrived with.
* @param message the <tt>Message</tt> that we're parsing
* <tt>binMessage</tt> into.
* @param offset the index where data starts in <tt>binMessage</tt>.
* @param msgLen the number of message bytes in <tt>binMessage</tt>.
* @param request the {@link Request} to validate.
* @param rawMessage the {@link RawMessage} containing the bytes of the
* {@link Request} so that we could check MESSAGE-INTEGRITY if necessary..
*
* @throws MessageDecodeException if there's something in the
* @throws IllegalArgumentException if there's something in the
* <tt>attribute</tt> that caused us to discard the whole message (e.g. an
* invalid checksum
* or username)
*/
private void performAttributeSpecificActions(Attribute attribute,
byte[] binMessage,
Message message,
int offset,
int msgLen)
throws MessageDecodeException
private void validateRequestAttributes(Request request,
RawMessage rawMessage)
throws IllegalArgumentException
{
///HANDLE OPTIONAL ATTRIBUTES
byte[] tranID = message.getTransactionID();
///HANDLE OPTIONAL ATTRIBUTES!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//assert valid username
if (attribute instanceof UsernameAttribute)
UsernameAttribute unameAttr = (UsernameAttribute)request
.getAttribute(Attribute.USERNAME);
if (unameAttr != null)
{
if (!validateUsername( (UsernameAttribute)attribute))
if (!validateUsername( unameAttr))
{
throw new MessageDecodeException(
throw new IllegalArgumentException(
"Non-recognized username: "
+ new String(((UsernameAttribute)attribute)
.getUsername()),
ErrorCodeAttribute.UNAUTHORIZED, tranID);
+ new String(unameAttr.getUsername()));
}
}
//assert Message Integrity
if (attribute instanceof MessageIntegrityAttribute)
MessageIntegrityAttribute msgIntAttr = (MessageIntegrityAttribute)
request.getAttribute(Attribute.MESSAGE_INTEGRITY);
if (msgIntAttr != null)
{
//we should complain if we have msg integrity and no username.
if (message.getAttribute(Attribute.USERNAME) == null)
if (unameAttr == null)
{
throw new MessageDecodeException(
"Missing USERNAME in the presence of MESSAGE-INTEGRITY: ",
ErrorCodeAttribute.BAD_REQUEST, tranID);
throw new IllegalArgumentException(
"Missing USERNAME in the presence of MESSAGE-INTEGRITY: ");
}
if (!validateMessageIntegrity((MessageIntegrityAttribute)attribute,
binMessage, offset, msgLen))
if (!validateMessageIntegrity(msgIntAttr,
new String(unameAttr.getUsername())
,rawMessage.getBytes(), 0))
{
throw new MessageDecodeException(
"Wrong MESSAGE-INTEGRITY value.",
ErrorCodeAttribute.UNAUTHORIZED, tranID);
throw new IllegalArgumentException(
"Wrong MESSAGE-INTEGRITY value.");
}
}
//check finger print CRC
if (attribute instanceof FingerprintAttribute)
{
if (!validateFingerprint((FingerprintAttribute)attribute,
binMessage, offset, msgLen))
{
//RFC 5389 says that we should ignore bad CRCs rather than
//reply with an error response.
throw new MessageDecodeException(
"Wrong value in FINGERPRINT");
}
}
}
/**
@ -712,32 +699,19 @@ public class StunStack
* {@link MessageIntegrityAttribute}.
*
* @param msgInt the attribute that we need to validate.
* @param username the user name that the message integrity checksum is
* supposed to have been built for.
* @param message the message whose SHA1 checksum we'd need to recalculate.
* @param offset the index in <tt>message</tt> where data starts.
* @param length the number of bytes in <tt>message</tt> that the SHA1 would
* need to be calculated over.
*
* @return <tt>true</tt> if <tt>msgInt</tt> contains a valid SHA1 value and
* <tt>false</tt> otherwise.
*/
private boolean validateMessageIntegrity(MessageIntegrityAttribute msgInt,
String username,
byte[] message,
int offset,
int length)
int offset)
{
//first get a password for the username specified with this message.
UsernameAttribute unameAttr
= (UsernameAttribute)getAttribute(Attribute.USERNAME);
if (unameAttr == null)
{
logger.info( "Received a message containing a "
+" MESSAGE-INTEGRITY attribute and no USERNAME");
return false;
}
String username = new String(unameAttr.getUsername());
int colon = username.indexOf(":");
if( username.length() < 1
@ -761,7 +735,8 @@ public class StunStack
//now check whether the SHA1 matches.
byte[] expectedSha1 = MessageIntegrityAttribute
.calculateHmacSha1(message, offset, length, key);
.calculateHmacSha1(
message, offset, msgInt.getLocationInMessage(), key);
if (!Arrays.equals(expectedSha1, msgInt.getHmacSha1Content()))
{

View File

@ -67,7 +67,7 @@ public class AttributeDecoderTest extends TestCase {
Transport.UDP));
Attribute actualReturn = AttributeDecoder.decode(
bytes, offset, length, null);
bytes, offset, length);
assertEquals(
"AttributeDecoder.decode() failed for a MAPPED-ADDRESS attribute",
@ -91,7 +91,7 @@ public class AttributeDecoderTest extends TestCase {
Transport.UDP));
Attribute actualReturn = AttributeDecoder.decode(
bytes, offset, length, null);
bytes, offset, length);
assertEquals(
"AttributeDecoder.decode() failed for a MAPPED-ADDRESS attribute",
@ -112,7 +112,7 @@ public class AttributeDecoderTest extends TestCase {
expectedReturn.setChangePortFlag(MsgFixture.CHANGE_PORT_FLAG_1);
Attribute actualReturn = AttributeDecoder.decode(
bytes, offset, length, null);
bytes, offset, length);
assertEquals("AttributeDecoder.decode() failed for a CHANGE-REQUEST attribute",
expectedReturn, actualReturn);
@ -134,7 +134,7 @@ public class AttributeDecoderTest extends TestCase {
expectedReturn.setReasonPhrase(MsgFixture.REASON_PHRASE);
Attribute actualReturn = AttributeDecoder.decode(
bytes, offset, length, null);
bytes, offset, length);
assertEquals(
"AttributeDecoder.decode() failed for a ERROR-CODE attribute",
expectedReturn, actualReturn);
@ -157,9 +157,10 @@ public class AttributeDecoderTest extends TestCase {
expectedReturn.addAttributeID(MsgFixture.UNKNOWN_ATTRIBUTES_3D_ATT);
Attribute actualReturn = AttributeDecoder.decode(
bytes, offset, length, null);
bytes, offset, length);
assertEquals("AttributeDecoder.decode() failed for a ERROR-CODE attribute",
assertEquals(
"AttributeDecoder.decode() failed for a ERROR-CODE attribute",
expectedReturn, actualReturn);
}
@ -179,7 +180,7 @@ public class AttributeDecoderTest extends TestCase {
expectedAttributeValue.length);
Attribute actualReturn = AttributeDecoder.decode(
bytes, offset, length, null);
bytes, offset, length);
assertEquals(
"AttributeDecoder.decode() failed for a UNKNOWN_OPTIONAL attribute",
expectedReturn, actualReturn);