Attempts to fix:

- incorrect calculations of the MESSAGE-INTEGRITY attribute value when sending and receiving (e.g. the connectivity checks) STUN messages,
- ArrayIndexOutOfBoundsException in EvenPortAttribute
- a failure to take the padded attribute length into account when encoding Message into bytes which would cause the STUN messages to be incorrectly encoded.
This commit is contained in:
lubomir.marinov 2010-06-25 17:41:58 +00:00
parent 316e524a0f
commit c859509daa
11 changed files with 296 additions and 94 deletions

View File

@ -30,5 +30,4 @@ public interface ResponseCollector
* transaction that has just failed. * transaction that has just failed.
*/ */
public void processTimeout(StunTimeoutEvent event); public void processTimeout(StunTimeoutEvent event);
} }

View File

@ -105,9 +105,6 @@ public class EvenPortAttribute extends Attribute
binValue[3] = (byte)(getDataLength() & 0x00FF); binValue[3] = (byte)(getDataLength() & 0x00FF);
//Data //Data
binValue[4] = (byte)(rFlag ? 1 << 8 : 0); binValue[4] = (byte)(rFlag ? 1 << 8 : 0);
binValue[5] = 0x00; /* not used for the moment */
binValue[6] = 0x00; /* not used for the moment */
binValue[7] = 0x00; /* not used for the moment */
return binValue; return binValue;
} }

View File

@ -28,8 +28,8 @@ class ConnectivityCheckClient
* The <tt>Logger</tt> used by the <tt>ConnectivityCheckClient</tt> * The <tt>Logger</tt> used by the <tt>ConnectivityCheckClient</tt>
* class and its instances for logging output. * class and its instances for logging output.
*/ */
private static final Logger logger = Logger private static final Logger logger
.getLogger(ConnectivityCheckClient.class.getName()); = Logger.getLogger(ConnectivityCheckClient.class.getName());
/** /**
* The agent that created us. * The agent that created us.
@ -82,8 +82,11 @@ class ConnectivityCheckClient
private void startChecks(CheckList checkList) private void startChecks(CheckList checkList)
{ {
PaceMaker paceMaker = new PaceMaker(this, checkList); PaceMaker paceMaker = new PaceMaker(this, checkList);
paceMakers.add(paceMaker);
synchronized (paceMakers)
{
paceMakers.add(paceMaker);
}
paceMaker.start(); paceMaker.start();
} }
@ -661,7 +664,12 @@ class ConnectivityCheckClient
} }
parentClient.paceMakers.remove(this); List<PaceMaker> parentClientPaceMakers = parentClient.paceMakers;
synchronized (parentClientPaceMakers)
{
parentClientPaceMakers.remove(this);
}
} }
} }
@ -673,6 +681,7 @@ class ConnectivityCheckClient
synchronized (paceMakers) synchronized (paceMakers)
{ {
Iterator<PaceMaker> paceMakersIter = paceMakers.iterator(); Iterator<PaceMaker> paceMakersIter = paceMakers.iterator();
while(paceMakersIter.hasNext()) while(paceMakersIter.hasNext())
{ {
PaceMaker paceMaker = paceMakersIter.next(); PaceMaker paceMaker = paceMakersIter.next();
@ -680,7 +689,6 @@ class ConnectivityCheckClient
paceMaker.isRunning = false; paceMaker.isRunning = false;
synchronized(paceMaker) synchronized(paceMaker)
{ {
paceMaker.notify(); paceMaker.notify();
} }

View File

@ -294,21 +294,20 @@ class ConnectivityCheckServer
*/ */
public boolean checkLocalUserName(String username) public boolean checkLocalUserName(String username)
{ {
boolean accept = false;
int colon = username.indexOf(":"); int colon = username.indexOf(":");
if( colon < 0) String ufrag;
if (colon < 0)
{ {
//caller gave us a ufrag //caller gave us a ufrag
if(username.equals(parentAgent.getLocalUfrag())) ufrag = username;
accept = true;
} }
else else
{ {
//caller gave us the entire username. //caller gave us the entire username.
if(username.substring(0, colon).equals(parentAgent.getLocalUfrag())) ufrag = username.substring(0, colon);
accept = true;
} }
return accept; return ufrag.equals(parentAgent.getLocalUfrag());
} }
/** /**
@ -324,23 +323,10 @@ class ConnectivityCheckServer
*/ */
public byte[] getLocalKey(String username) public byte[] getLocalKey(String username)
{ {
//support both the case where username is the local fragment or the return
//entire user name. checkLocalUserName(username)
int colon = username.indexOf(":"); ? parentAgent.getLocalPassword().getBytes()
if( colon < 0) : null;
{
//caller gave us a ufrag
if (username.equals(parentAgent.getLocalUfrag()))
return parentAgent.getLocalPassword().getBytes();
}
else
{
//caller gave us the entire username.
if(username.substring(0, colon).equals(parentAgent.getLocalUfrag()))
return parentAgent.getLocalPassword().getBytes();
}
return null;
} }
/** /**
@ -359,7 +345,8 @@ class ConnectivityCheckServer
//support both the case where username is the local fragment or the //support both the case where username is the local fragment or the
//entire user name. //entire user name.
int colon = username.indexOf(":"); int colon = username.indexOf(":");
if( colon < 0)
if (colon < 0)
{ {
//caller gave us a ufrag //caller gave us a ufrag
if (username.equals(parentAgent.getRemoteUfrag())) if (username.equals(parentAgent.getRemoteUfrag()))
@ -371,7 +358,6 @@ class ConnectivityCheckServer
if (username.equals(parentAgent.generateLocalUserName())) if (username.equals(parentAgent.generateLocalUserName()))
return parentAgent.getRemotePassword().getBytes(); return parentAgent.getRemotePassword().getBytes();
} }
return null; return null;
} }

View File

@ -262,14 +262,13 @@ public abstract class Message
for (Attribute att : attributes.values()) for (Attribute att : attributes.values())
{ {
int attLen = att.getDataLength() + Attribute.HEADER_LENGTH; int attLen = att.getDataLength() + Attribute.HEADER_LENGTH;
//take attribute padding into account: //take attribute padding into account:
attLen += (4 - attLen%4)%4; attLen += (4 - attLen%4)%4;
length += attLen; length += attLen;
} }
return length; return length;
} }
@ -490,6 +489,8 @@ public abstract class Message
switch (messageType) switch (messageType)
{ {
case ALLOCATE_REQUEST: return "ALLOCATE-REQUEST"; case ALLOCATE_REQUEST: return "ALLOCATE-REQUEST";
case ALLOCATE_RESPONSE: return "ALLOCATE-RESPONSE";
case ALLOCATE_ERROR_RESPONSE: return "ALLOCATE-ERROR-RESPONSE";
case BINDING_REQUEST: return "BINDING-REQUEST"; case BINDING_REQUEST: return "BINDING-REQUEST";
case BINDING_SUCCESS_RESPONSE: return "BINDING-RESPONSE"; case BINDING_SUCCESS_RESPONSE: return "BINDING-RESPONSE";
case BINDING_ERROR_RESPONSE: return "BINDING-ERROR-RESPONSE"; case BINDING_ERROR_RESPONSE: return "BINDING-ERROR-RESPONSE";
@ -547,18 +548,21 @@ public abstract class Message
{ {
prepareForEncoding(); prepareForEncoding();
//make sure that
//make sure we have everything necessary to encode a proper message //make sure we have everything necessary to encode a proper message
validateAttributePresentity(); validateAttributePresentity();
char dataLength = getDataLength();
final char dataLength = getDataLength();
byte binMsg[] = new byte[HEADER_LENGTH + dataLength]; byte binMsg[] = new byte[HEADER_LENGTH + dataLength];
int offset = 0; int offset = 0;
// STUN Message Type
binMsg[offset++] = (byte)(getMessageType()>>8); binMsg[offset++] = (byte)(getMessageType()>>8);
binMsg[offset++] = (byte)(getMessageType()&0xFF); binMsg[offset++] = (byte)(getMessageType()&0xFF);
binMsg[offset++] = (byte)(dataLength >> 8); // Message Length
binMsg[offset++] = (byte)(dataLength & 0xFF); final int messageLengthOffset = offset;
offset += 2;
System.arraycopy(MAGIC_COOKIE, 0, binMsg, offset, 4); System.arraycopy(MAGIC_COOKIE, 0, binMsg, offset, 4);
offset+=4; offset+=4;
@ -568,27 +572,54 @@ public abstract class Message
Iterator<Map.Entry<Character, Attribute>> iter Iterator<Map.Entry<Character, Attribute>> iter
= attributes.entrySet().iterator(); = attributes.entrySet().iterator();
char dataLengthForContentDependentAttribute = 0;
while (iter.hasNext()) while (iter.hasNext())
{ {
Attribute attribute = iter.next().getValue(); Attribute attribute = iter.next().getValue();
int attributeLength
= attribute.getDataLength() + Attribute.HEADER_LENGTH;
//take attribute padding into account:
attributeLength += (4 - attributeLength % 4) % 4;
dataLengthForContentDependentAttribute += attributeLength;
//special handling for message integrity and fingerprint values //special handling for message integrity and fingerprint values
byte[] attBinValue; byte[] binAtt;
if (attribute instanceof ContentDependentAttribute) if (attribute instanceof ContentDependentAttribute)
{ {
attBinValue = ((ContentDependentAttribute)attribute) /*
.encode(binMsg, 0, offset); * The "Message Length" seen by a ContentDependentAttribute is
* upto and including the very Attribute but without any other
* Attribute instances after it.
*/
binMsg[messageLengthOffset]
= (byte)(dataLengthForContentDependentAttribute >> 8);
binMsg[messageLengthOffset + 1]
= (byte)(dataLengthForContentDependentAttribute & 0xFF);
binAtt
= ((ContentDependentAttribute)attribute).encode(
binMsg, 0, offset);
} }
else else
{ {
attBinValue = attribute.encode(); binAtt = attribute.encode();
} }
System.arraycopy( System.arraycopy(binAtt, 0, binMsg, offset, binAtt.length);
attBinValue, 0, binMsg, offset, attBinValue.length); /*
offset += attBinValue.length; * Offset by attributeLength and not by binAtt.length because
* attributeLength takes the attribute padding into account and
* binAtt.length does not.
*/
offset += attributeLength;
} }
// Message Length
binMsg[messageLengthOffset] = (byte)(dataLength >> 8);
binMsg[messageLengthOffset + 1] = (byte)(dataLength & 0xFF);
return binMsg; return binMsg;
} }

View File

@ -352,24 +352,24 @@ public class MessageFactory
/* XXX add enum somewhere for transport number */ /* XXX add enum somewhere for transport number */
if (protocol != 6 && protocol != 17) if (protocol != 6 && protocol != 17)
{
throw new StunException("Protocol not valid!"); throw new StunException("Protocol not valid!");
// REQUESTED-TRANSPORT
allocateRequest.addAttribute(
AttributeFactory.createRequestedTransportAttribute(
protocol));
// EVEN-PORT
if (rFlag)
{
allocateRequest.addAttribute(
AttributeFactory.createEvenPortAttribute(rFlag));
} }
}
/* add a REQUESTED-TRANSPORT attribute */ catch (StunException ex)
RequestedTransportAttribute reqTransport = AttributeFactory
.createRequestedTransportAttribute(protocol);
allocateRequest.addAttribute(reqTransport);
/* add EVEN-PORT attribute */
EvenPortAttribute reqProps = AttributeFactory
.createEvenPortAttribute(rFlag);
allocateRequest.addAttribute(reqProps);
} catch (StunException ex)
{ {
logger.log(Level.FINE, "Failed to set message type.", ex); logger.log(Level.FINE, "Failed to set message type.", ex);
} }
return allocateRequest; return allocateRequest;
} }

View File

@ -0,0 +1,141 @@
/*
* 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.security;
import java.io.*;
import java.lang.reflect.*;
/**
* Represents a STUN long-term credential.
*
* @author Lubomir Marinov
*/
public class LongTermCredential
{
/**
* Encodes a specific <tt>String</tt> into a sequence of <tt>byte</tt>s
* using the UTF-8 charset, storing the result into a new <tt>byte</tt>
* array.
*
* @param s the <tt>String</tt> to encode
* @return a new array of <tt>byte</tt>s which represents the encoding of
* the specified <tt>String</tt> using the UTF-8 charset
*/
public static byte[] getBytes(String s)
{
if (s == null)
return null;
else
{
try
{
return s.getBytes("UTF-8");
}
catch (UnsupportedEncodingException ueex)
{
throw new UndeclaredThrowableException(ueex);
}
}
}
/**
* Constructs a new <tt>String</tt> by decoding a specific array of
* <tt>byte</tt>s using the UTF-8 charset. The length of the new
* <tt>String</tt> is a function of the charset, and hence may not be equal
* to the length of the <tt>byte</tt> array.
*
* @param bytes the <tt>byte</tt>s to be decoded into characters
* @return a new <tt>String</tt> which has been decoded from the specified
* array of <tt>byte</tt>s using the UTF-8 charset
*/
public static String toString(byte[] bytes)
{
if (bytes == null)
return null;
else
{
try
{
return new String(bytes, "UTF-8");
}
catch (UnsupportedEncodingException ueex)
{
throw new UndeclaredThrowableException(ueex);
}
}
}
/**
* The password of this <tt>LongTermCredential</tt>.
*/
private final byte[] password;
/**
* The username of this <tt>LongTermCredential</tt>.
*/
private final byte[] username;
/**
* Initializes a new <tt>LongTermCredential</tt> instance with no username
* and no password. Extenders should override {@link #getUsername()} and
* {@link #getPassword()} to provide the username and the password,
* respectively, when requested.
*/
protected LongTermCredential()
{
this((byte[]) null, (byte[]) null);
}
/**
* Initializes a new <tt>LongTermCredential</tt> instance with a specific
* username and a specific password.
*
* @param username the username to initialize the new instance with
* @param password the password to initialize the new instance with
*/
public LongTermCredential(byte[] username, byte[] password)
{
this.username = (username == null) ? null : username.clone();
this.password = (password == null) ? null : password.clone();
}
/**
* Initializes a new <tt>LongTermCredential</tt> instance with a specific
* username and a specific password.
*
* @param username the username to initialize the new instance with
* @param password the password to initialize the new instance with
*/
public LongTermCredential(String username, String password)
{
this(getBytes(username), getBytes(password));
}
/**
* Gets the password of this <tt>LongTermCredential</tt>.
*
* @return an array of <tt>byte</tt>s which represents the password of this
* <tt>LongTermCredential</tt>
*/
public byte[] getPassword()
{
return (password == null) ? null : password.clone();
}
/**
* Gets the username of this <tt>LongTermCredential</tt>.
*
* @return an array of <tt>byte</tt>s which represents the username of this
* <tt>LongTermCredential</tt>
*/
public byte[] getUsername()
{
return (username == null) ? null : username.clone();
}
}

View File

@ -372,8 +372,11 @@ public class MultiplexingDatagramSocket
{ {
socket.received.add(clone(p)); socket.received.add(clone(p));
accepted = true; accepted = true;
//emil: don't break, we want all
//filtering sockets to get this /*
* Emil: Don't break because we want all
* filtering sockets to get this.
*/
//break; //break;
} }

View File

@ -31,6 +31,16 @@ public class StunDatagramPacketFilter
*/ */
protected final TransportAddress stunServer; protected final TransportAddress stunServer;
/**
* Initializes a new <tt>StunDatagramPacketFilter</tt> which will accept
* <tt>DatagramPacket</tt>s which represent STUN messages received from
* any destination.
*/
public StunDatagramPacketFilter()
{
this(null);
}
/** /**
* Initializes a new <tt>StunDatagramPacketFilter</tt> which will accept * Initializes a new <tt>StunDatagramPacketFilter</tt> which will accept
* <tt>DatagramPacket</tt>s which represent STUN messages and which are part * <tt>DatagramPacket</tt>s which represent STUN messages and which are part
@ -47,16 +57,6 @@ public class StunDatagramPacketFilter
this.stunServer = stunServer; this.stunServer = stunServer;
} }
/**
* Initializes a new <tt>StunDatagramPacketFilter</tt> which will accept
* <tt>DatagramPacket</tt>s which represent STUN messages received from
* any destination.
*/
public StunDatagramPacketFilter()
{
this(null);
}
/** /**
* Determines whether a specific <tt>DatagramPacket</tt> represents a STUN * Determines whether a specific <tt>DatagramPacket</tt> represents a STUN
* message and whether it is part of the communication with the STUN server * message and whether it is part of the communication with the STUN server
@ -71,13 +71,12 @@ public class StunDatagramPacketFilter
*/ */
public boolean accept(DatagramPacket p) public boolean accept(DatagramPacket p)
{ {
//if we were instantiated for a specific stun server, and the packet /*
//did not originate there, we reject it. * If we were instantiated for a specific STUN server, and the packet
if (stunServer != null * did not originate there, we reject it.
&& !stunServer.equals(p.getSocketAddress())) */
{ if ((stunServer != null) && !stunServer.equals(p.getSocketAddress()))
return false; return false;
}
/* /*
* All STUN messages MUST start with a 20-byte header followed by * All STUN messages MUST start with a 20-byte header followed by

View File

@ -252,7 +252,8 @@ class StunClientTransaction
return; return;
stackCallback.removeClientTransaction(this); stackCallback.removeClientTransaction(this);
responseCollector.processTimeout( new StunTimeoutEvent( responseCollector.processTimeout(
new StunTimeoutEvent(
this.request, getLocalAddress(), transactionID)); this.request, getLocalAddress(), transactionID));
} }
} }

View File

@ -714,7 +714,7 @@ public class StunStack
if (!validateMessageIntegrity(msgIntAttr, if (!validateMessageIntegrity(msgIntAttr,
new String(unameAttr.getUsername()), new String(unameAttr.getUsername()),
evt.getRawMessage().getBytes(), 0)) evt.getRawMessage()))
{ {
Response error = MessageFactory.createBindingErrorResponse( Response error = MessageFactory.createBindingErrorResponse(
ErrorCodeAttribute.UNAUTHORIZED, ErrorCodeAttribute.UNAUTHORIZED,
@ -777,20 +777,18 @@ public class StunStack
* @param username the user name that the message integrity checksum is * @param username the user name that the message integrity checksum is
* supposed to have been built for. * supposed to have been built for.
* @param message the message whose SHA1 checksum we'd need to recalculate. * @param message the message whose SHA1 checksum we'd need to recalculate.
* @param offset the index in <tt>message</tt> where data starts.
* *
* @return <tt>true</tt> if <tt>msgInt</tt> contains a valid SHA1 value and * @return <tt>true</tt> if <tt>msgInt</tt> contains a valid SHA1 value and
* <tt>false</tt> otherwise. * <tt>false</tt> otherwise.
*/ */
private boolean validateMessageIntegrity(MessageIntegrityAttribute msgInt, private boolean validateMessageIntegrity(
String username, MessageIntegrityAttribute msgInt,
byte[] message, String username,
int offset) RawMessage message)
{ {
int colon = username.indexOf(":"); int colon = username.indexOf(":");
if( username.length() < 1 if( (username.length() < 1) || colon < 1)
|| colon < 1)
{ {
if(logger.isLoggable(Level.FINE)) if(logger.isLoggable(Level.FINE))
{ {
@ -808,12 +806,52 @@ public class StunStack
if(key == null) if(key == null)
return false; return false;
//now check whether the SHA1 matches. /*
byte[] expectedSha1 = MessageIntegrityAttribute * Now check whether the SHA1 matches. Using
.calculateHmacSha1( * MessageIntegrityAttribute.calculateHmacSha1 on the bytes of the
message, offset, msgInt.getLocationInMessage(), key); * RawMessage will be incorrect if there are other Attributes after the
* MessageIntegrityAttribute because the value of the
* MessageIntegrityAttribute is calculated on a STUN "Message Length"
* upto and including the MESSAGE-INTEGRITY and excluding any Attributes
* after it. So for the sake of preventing code duplication, clone the
* message and calculate the expected MESSAGE-INTEGRITY in the clone.
*/
MessageIntegrityAttribute expectedMsgInt;
if (!Arrays.equals(expectedSha1, msgInt.getHmacSha1Content())) try
{
Message decodedMessage
= Message.decode(
message.getBytes(),
(char) 0,
(char) message.getMessageLength());
expectedMsgInt
= (MessageIntegrityAttribute)
decodedMessage.getAttribute(Attribute.MESSAGE_INTEGRITY);
if (expectedMsgInt != null)
{
/*
* Encode the decodedMessage so that its
* MessageIntegrityAttribute populates with the expectedSha1.
* But don't forget to set the username of the
* MessageIntegrityAttribute first or its encoding will crash.
*/
expectedMsgInt.setUsername(lfrag);
decodedMessage.encode();
}
}
catch (StunException sex)
{
expectedMsgInt = null;
}
if ((expectedMsgInt == null)
|| !Arrays.equals(
expectedMsgInt.getHmacSha1Content(),
msgInt.getHmacSha1Content()))
{ {
if(logger.isLoggable(Level.FINE)) if(logger.isLoggable(Level.FINE))
{ {
@ -826,7 +864,6 @@ public class StunStack
if (logger.isLoggable(Level.FINEST)) if (logger.isLoggable(Level.FINEST))
logger.finest("Successfully verified msg integrity"); logger.finest("Successfully verified msg integrity");
return true; return true;
} }