diff --git a/src/org/ice4j/StunMessageEvent.java b/src/org/ice4j/StunMessageEvent.java index 75e23ce..aa060af 100644 --- a/src/org/ice4j/StunMessageEvent.java +++ b/src/org/ice4j/StunMessageEvent.java @@ -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 TransportAddress 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; + } } diff --git a/src/org/ice4j/attribute/Attribute.java b/src/org/ice4j/attribute/Attribute.java index 6a63cfb..cab11ca 100644 --- a/src/org/ice4j/attribute/Attribute.java +++ b/src/org/ice4j/attribute/Attribute.java @@ -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. * diff --git a/src/org/ice4j/attribute/AttributeDecoder.java b/src/org/ice4j/attribute/AttributeDecoder.java index a4a563b..ee471fa 100644 --- a/src/org/ice4j/attribute/AttributeDecoder.java +++ b/src/org/ice4j/attribute/AttributeDecoder.java @@ -122,6 +122,7 @@ public class AttributeDecoder } decodedAttribute.setAttributeType(attributeType); + decodedAttribute.setLocationInMessage(offset); decodedAttribute.decodeAttributeBody(bytes, (char)(Attribute.HEADER_LENGTH + offset), attributeLength); diff --git a/src/org/ice4j/message/Message.java b/src/org/ice4j/message/Message.java index 1067942..704e946 100644 --- a/src/org/ice4j/message/Message.java +++ b/src/org/ice4j/message/Message.java @@ -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 Attribute we'd like to process. + * @param binMessage the byte array that the message arrived with. + * @param offset the index where data starts in binMessage. + * @param msgLen the number of message bytes in binMessage. + * + * @throws StunException if there's something in the + * attribute 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 message + * 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 message where data starts. + * @param length the number of bytes in message that the CRC32 + * would need to be calculated over. + * + * @return true if FINGERPRINT contains a valid CRC32 + * value and false 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 message 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 message where data starts. + * @param length the number of bytes in message that the SHA1 would + * need to be calculated over. + * + * @return true if msgInt contains a valid SHA1 value and + * false 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 + * unameAttr. + * + * @param unameAttr the attribute that we need to validate. + * + * @return true if unameAttr contains a valid user name + * and false 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. diff --git a/src/org/ice4j/message/MessageDecodeException.java b/src/org/ice4j/message/MessageDecodeException.java deleted file mode 100644 index 0a11ed0..0000000 --- a/src/org/ice4j/message/MessageDecodeException.java +++ /dev/null @@ -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 MessageDecodeException instance. - * - * @param message a text message explaining the exception - */ - public MessageDecodeException(String message) - { - super(message); - } - - /** - * Creates a new MessageDecodeException 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 MessageDecodeException 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 -1 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 MessageDecodeException 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 -1 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; - } -} diff --git a/src/org/ice4j/stack/MessageProcessor.java b/src/org/ice4j/stack/MessageProcessor.java index d2ac4a3..cdb3d95 100644 --- a/src/org/ice4j/stack/MessageProcessor.java +++ b/src/org/ice4j/stack/MessageProcessor.java @@ -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); } diff --git a/src/org/ice4j/stack/RawMessage.java b/src/org/ice4j/stack/RawMessage.java index 8f17309..6694630 100644 --- a/src/org/ice4j/stack/RawMessage.java +++ b/src/org/ice4j/stack/RawMessage.java @@ -15,7 +15,7 @@ import org.ice4j.*; * * @author Emil Ivov */ -class RawMessage +public class RawMessage { /** * The message itself. diff --git a/src/org/ice4j/stack/StunStack.java b/src/org/ice4j/stack/StunStack.java index 51f00da..bf5ffa5 100644 --- a/src/org/ice4j/stack/StunStack.java +++ b/src/org/ice4j/stack/StunStack.java @@ -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 Attribute we'd like to process. - * @param binMessage the byte array that the message arrived with. - * @param message the Message that we're parsing - * binMessage into. - * @param offset the index where data starts in binMessage. - * @param msgLen the number of message bytes in binMessage. + * @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 * attribute 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 message where data starts. - * @param length the number of bytes in message that the SHA1 would - * need to be calculated over. * * @return true if msgInt contains a valid SHA1 value and * false 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())) { diff --git a/test/org/ice4j/attribute/AttributeDecoderTest.java b/test/org/ice4j/attribute/AttributeDecoderTest.java index 23f976e..c672c0c 100644 --- a/test/org/ice4j/attribute/AttributeDecoderTest.java +++ b/test/org/ice4j/attribute/AttributeDecoderTest.java @@ -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);