diff --git a/src/org/ice4j/ResponseCollector.java b/src/org/ice4j/ResponseCollector.java index 0b6abcb..8936743 100644 --- a/src/org/ice4j/ResponseCollector.java +++ b/src/org/ice4j/ResponseCollector.java @@ -30,5 +30,4 @@ public interface ResponseCollector * transaction that has just failed. */ public void processTimeout(StunTimeoutEvent event); - } diff --git a/src/org/ice4j/attribute/EvenPortAttribute.java b/src/org/ice4j/attribute/EvenPortAttribute.java index fb65fd0..eb5ee3f 100644 --- a/src/org/ice4j/attribute/EvenPortAttribute.java +++ b/src/org/ice4j/attribute/EvenPortAttribute.java @@ -105,9 +105,6 @@ public class EvenPortAttribute extends Attribute binValue[3] = (byte)(getDataLength() & 0x00FF); //Data 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; } diff --git a/src/org/ice4j/ice/ConnectivityCheckClient.java b/src/org/ice4j/ice/ConnectivityCheckClient.java index 30fb9f7..b05054e 100644 --- a/src/org/ice4j/ice/ConnectivityCheckClient.java +++ b/src/org/ice4j/ice/ConnectivityCheckClient.java @@ -28,8 +28,8 @@ class ConnectivityCheckClient * The Logger used by the ConnectivityCheckClient * class and its instances for logging output. */ - private static final Logger logger = Logger - .getLogger(ConnectivityCheckClient.class.getName()); + private static final Logger logger + = Logger.getLogger(ConnectivityCheckClient.class.getName()); /** * The agent that created us. @@ -82,8 +82,11 @@ class ConnectivityCheckClient private void startChecks(CheckList checkList) { PaceMaker paceMaker = new PaceMaker(this, checkList); - paceMakers.add(paceMaker); + synchronized (paceMakers) + { + paceMakers.add(paceMaker); + } paceMaker.start(); } @@ -661,7 +664,12 @@ class ConnectivityCheckClient } - parentClient.paceMakers.remove(this); + List parentClientPaceMakers = parentClient.paceMakers; + + synchronized (parentClientPaceMakers) + { + parentClientPaceMakers.remove(this); + } } } @@ -673,6 +681,7 @@ class ConnectivityCheckClient synchronized (paceMakers) { Iterator paceMakersIter = paceMakers.iterator(); + while(paceMakersIter.hasNext()) { PaceMaker paceMaker = paceMakersIter.next(); @@ -680,7 +689,6 @@ class ConnectivityCheckClient paceMaker.isRunning = false; synchronized(paceMaker) { - paceMaker.notify(); } diff --git a/src/org/ice4j/ice/ConnectivityCheckServer.java b/src/org/ice4j/ice/ConnectivityCheckServer.java index 29ea5f4..beca343 100644 --- a/src/org/ice4j/ice/ConnectivityCheckServer.java +++ b/src/org/ice4j/ice/ConnectivityCheckServer.java @@ -294,21 +294,20 @@ class ConnectivityCheckServer */ public boolean checkLocalUserName(String username) { - boolean accept = false; int colon = username.indexOf(":"); - if( colon < 0) + String ufrag; + + if (colon < 0) { //caller gave us a ufrag - if(username.equals(parentAgent.getLocalUfrag())) - accept = true; + ufrag = username; } else { //caller gave us the entire username. - if(username.substring(0, colon).equals(parentAgent.getLocalUfrag())) - accept = true; + ufrag = username.substring(0, colon); } - return accept; + return ufrag.equals(parentAgent.getLocalUfrag()); } /** @@ -324,23 +323,10 @@ class ConnectivityCheckServer */ public byte[] getLocalKey(String username) { - //support both the case where username is the local fragment or the - //entire user name. - int colon = username.indexOf(":"); - if( colon < 0) - { - //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; + return + checkLocalUserName(username) + ? parentAgent.getLocalPassword().getBytes() + : null; } /** @@ -359,7 +345,8 @@ class ConnectivityCheckServer //support both the case where username is the local fragment or the //entire user name. int colon = username.indexOf(":"); - if( colon < 0) + + if (colon < 0) { //caller gave us a ufrag if (username.equals(parentAgent.getRemoteUfrag())) @@ -371,7 +358,6 @@ class ConnectivityCheckServer if (username.equals(parentAgent.generateLocalUserName())) return parentAgent.getRemotePassword().getBytes(); } - return null; } diff --git a/src/org/ice4j/message/Message.java b/src/org/ice4j/message/Message.java index cd3ed06..ff0ebf9 100644 --- a/src/org/ice4j/message/Message.java +++ b/src/org/ice4j/message/Message.java @@ -262,14 +262,13 @@ public abstract class Message for (Attribute att : attributes.values()) { - int attLen = att.getDataLength() + Attribute.HEADER_LENGTH; + int attLen = att.getDataLength() + Attribute.HEADER_LENGTH; //take attribute padding into account: attLen += (4 - attLen%4)%4; length += attLen; } - return length; } @@ -490,6 +489,8 @@ public abstract class Message switch (messageType) { 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_SUCCESS_RESPONSE: return "BINDING-RESPONSE"; case BINDING_ERROR_RESPONSE: return "BINDING-ERROR-RESPONSE"; @@ -547,18 +548,21 @@ public abstract class Message { prepareForEncoding(); - //make sure that //make sure we have everything necessary to encode a proper message validateAttributePresentity(); - char dataLength = getDataLength(); + + final char dataLength = getDataLength(); byte binMsg[] = new byte[HEADER_LENGTH + dataLength]; int offset = 0; + // STUN Message Type binMsg[offset++] = (byte)(getMessageType()>>8); binMsg[offset++] = (byte)(getMessageType()&0xFF); - binMsg[offset++] = (byte)(dataLength >> 8); - binMsg[offset++] = (byte)(dataLength & 0xFF); + // Message Length + final int messageLengthOffset = offset; + + offset += 2; System.arraycopy(MAGIC_COOKIE, 0, binMsg, offset, 4); offset+=4; @@ -568,27 +572,54 @@ public abstract class Message Iterator> iter = attributes.entrySet().iterator(); + char dataLengthForContentDependentAttribute = 0; + while (iter.hasNext()) { 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 - byte[] attBinValue; + byte[] binAtt; + 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 { - attBinValue = attribute.encode(); + binAtt = attribute.encode(); } - System.arraycopy( - attBinValue, 0, binMsg, offset, attBinValue.length); - offset += attBinValue.length; + System.arraycopy(binAtt, 0, binMsg, offset, binAtt.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; } diff --git a/src/org/ice4j/message/MessageFactory.java b/src/org/ice4j/message/MessageFactory.java index 0c67447..5ab5648 100644 --- a/src/org/ice4j/message/MessageFactory.java +++ b/src/org/ice4j/message/MessageFactory.java @@ -352,24 +352,24 @@ public class MessageFactory /* XXX add enum somewhere for transport number */ if (protocol != 6 && protocol != 17) - { 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 */ - RequestedTransportAttribute reqTransport = AttributeFactory - .createRequestedTransportAttribute(protocol); - allocateRequest.addAttribute(reqTransport); - - /* add EVEN-PORT attribute */ - EvenPortAttribute reqProps = AttributeFactory - .createEvenPortAttribute(rFlag); - allocateRequest.addAttribute(reqProps); - } catch (StunException ex) + } + catch (StunException ex) { logger.log(Level.FINE, "Failed to set message type.", ex); } - return allocateRequest; } diff --git a/src/org/ice4j/security/LongTermCredential.java b/src/org/ice4j/security/LongTermCredential.java new file mode 100644 index 0000000..c42a052 --- /dev/null +++ b/src/org/ice4j/security/LongTermCredential.java @@ -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 String into a sequence of bytes + * using the UTF-8 charset, storing the result into a new byte + * array. + * + * @param s the String to encode + * @return a new array of bytes which represents the encoding of + * the specified String 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 String by decoding a specific array of + * bytes using the UTF-8 charset. The length of the new + * String is a function of the charset, and hence may not be equal + * to the length of the byte array. + * + * @param bytes the bytes to be decoded into characters + * @return a new String which has been decoded from the specified + * array of bytes 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 LongTermCredential. + */ + private final byte[] password; + + /** + * The username of this LongTermCredential. + */ + private final byte[] username; + + /** + * Initializes a new LongTermCredential 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 LongTermCredential 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 LongTermCredential 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 LongTermCredential. + * + * @return an array of bytes which represents the password of this + * LongTermCredential + */ + public byte[] getPassword() + { + return (password == null) ? null : password.clone(); + } + + /** + * Gets the username of this LongTermCredential. + * + * @return an array of bytes which represents the username of this + * LongTermCredential + */ + public byte[] getUsername() + { + return (username == null) ? null : username.clone(); + } +} diff --git a/src/org/ice4j/socket/MultiplexingDatagramSocket.java b/src/org/ice4j/socket/MultiplexingDatagramSocket.java index 5f9ca20..3ba1cb4 100644 --- a/src/org/ice4j/socket/MultiplexingDatagramSocket.java +++ b/src/org/ice4j/socket/MultiplexingDatagramSocket.java @@ -372,8 +372,11 @@ public class MultiplexingDatagramSocket { socket.received.add(clone(p)); 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; } diff --git a/src/org/ice4j/socket/StunDatagramPacketFilter.java b/src/org/ice4j/socket/StunDatagramPacketFilter.java index d3790af..d218d05 100644 --- a/src/org/ice4j/socket/StunDatagramPacketFilter.java +++ b/src/org/ice4j/socket/StunDatagramPacketFilter.java @@ -31,6 +31,16 @@ public class StunDatagramPacketFilter */ protected final TransportAddress stunServer; + /** + * Initializes a new StunDatagramPacketFilter which will accept + * DatagramPackets which represent STUN messages received from + * any destination. + */ + public StunDatagramPacketFilter() + { + this(null); + } + /** * Initializes a new StunDatagramPacketFilter which will accept * DatagramPackets which represent STUN messages and which are part @@ -47,16 +57,6 @@ public class StunDatagramPacketFilter this.stunServer = stunServer; } - /** - * Initializes a new StunDatagramPacketFilter which will accept - * DatagramPackets which represent STUN messages received from - * any destination. - */ - public StunDatagramPacketFilter() - { - this(null); - } - /** * Determines whether a specific DatagramPacket represents a STUN * 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) { - //if we were instantiated for a specific stun server, and the packet - //did not originate there, we reject it. - if (stunServer != null - && !stunServer.equals(p.getSocketAddress())) - { + /* + * If we were instantiated for a specific STUN server, and the packet + * did not originate there, we reject it. + */ + if ((stunServer != null) && !stunServer.equals(p.getSocketAddress())) return false; - } /* * All STUN messages MUST start with a 20-byte header followed by diff --git a/src/org/ice4j/stack/StunClientTransaction.java b/src/org/ice4j/stack/StunClientTransaction.java index aa8eea4..7c665f9 100644 --- a/src/org/ice4j/stack/StunClientTransaction.java +++ b/src/org/ice4j/stack/StunClientTransaction.java @@ -252,7 +252,8 @@ class StunClientTransaction return; stackCallback.removeClientTransaction(this); - responseCollector.processTimeout( new StunTimeoutEvent( + responseCollector.processTimeout( + new StunTimeoutEvent( this.request, getLocalAddress(), transactionID)); } } diff --git a/src/org/ice4j/stack/StunStack.java b/src/org/ice4j/stack/StunStack.java index 47f3180..bd42c7f 100644 --- a/src/org/ice4j/stack/StunStack.java +++ b/src/org/ice4j/stack/StunStack.java @@ -714,7 +714,7 @@ public class StunStack if (!validateMessageIntegrity(msgIntAttr, new String(unameAttr.getUsername()), - evt.getRawMessage().getBytes(), 0)) + evt.getRawMessage())) { Response error = MessageFactory.createBindingErrorResponse( ErrorCodeAttribute.UNAUTHORIZED, @@ -777,20 +777,18 @@ public class StunStack * @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. * * @return true if msgInt contains a valid SHA1 value and * false otherwise. */ - private boolean validateMessageIntegrity(MessageIntegrityAttribute msgInt, - String username, - byte[] message, - int offset) + private boolean validateMessageIntegrity( + MessageIntegrityAttribute msgInt, + String username, + RawMessage message) { int colon = username.indexOf(":"); - if( username.length() < 1 - || colon < 1) + if( (username.length() < 1) || colon < 1) { if(logger.isLoggable(Level.FINE)) { @@ -808,12 +806,52 @@ public class StunStack if(key == null) return false; - //now check whether the SHA1 matches. - byte[] expectedSha1 = MessageIntegrityAttribute - .calculateHmacSha1( - message, offset, msgInt.getLocationInMessage(), key); + /* + * Now check whether the SHA1 matches. Using + * MessageIntegrityAttribute.calculateHmacSha1 on the bytes of the + * 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)) { @@ -826,7 +864,6 @@ public class StunStack if (logger.isLoggable(Level.FINEST)) logger.finest("Successfully verified msg integrity"); - return true; }