diff --git a/src/org/ice4j/ice/Agent.java b/src/org/ice4j/ice/Agent.java
index 3457c7b..600b13a 100644
--- a/src/org/ice4j/ice/Agent.java
+++ b/src/org/ice4j/ice/Agent.java
@@ -337,7 +337,7 @@ public class Agent
* @return that password that should be advertised in session descriptions
* containing ICE data from this agent.
*/
- public String getPassword()
+ public String getLocalPassword()
{
return password;
}
@@ -401,7 +401,7 @@ public class Agent
}
/**
- * Returns the user name that we should respect a peer Agent to use
+ * Returns the user name that we should tell a peer Agent to use
* in connectivity checks for outgoing Binding Requests. According to RFC
* 5245, a Binding Request serving as a connectivity check MUST utilize the
* STUN short term credential mechanism. The username for the credential is
@@ -511,7 +511,7 @@ public class Agent
{
StringBuffer buff = new StringBuffer("ICE Agent (stream-count=");
- buff.append(getStreamCount()).append(" ice-pwd:").append(getPassword());
+ buff.append(getStreamCount()).append(" ice-pwd:").append(getLocalPassword());
buff.append(getStreamCount()).append(" ice-ufrag:")
.append(getLocalUfrag());
buff.append(getStreamCount()).append(" tie-breaker:" + getTieBreaker());
diff --git a/src/org/ice4j/ice/ConnectivityCheckHandler.java b/src/org/ice4j/ice/ConnectivityCheckHandler.java
new file mode 100644
index 0000000..60c9c5b
--- /dev/null
+++ b/src/org/ice4j/ice/ConnectivityCheckHandler.java
@@ -0,0 +1,277 @@
+/*
+ * 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.ice;
+
+import java.net.*;
+import java.util.logging.*;
+
+import org.ice4j.*;
+import org.ice4j.attribute.*;
+import org.ice4j.message.*;
+import org.ice4j.security.*;
+import org.ice4j.socket.*;
+import org.ice4j.stack.*;
+
+/**
+ * @author Emil Ivov
+ */
+public class ConnectivityCheckHandler
+ implements ResponseCollector,
+ RequestListener,
+ CredentialsAuthority
+{
+ /**
+ * The Logger used by the ConnectivityCheckClient
+ * class and its instances for logging output.
+ */
+ private static final Logger logger = Logger
+ .getLogger(ConnectivityCheckHandler.class.getName());
+
+ /**
+ * The agent that created us.
+ */
+ private final Agent parentAgent;
+
+ /**
+ * The stun stack that we will use for connectivity checks.
+ */
+ StunStack stunStack = StunStack.getInstance();
+
+ /**
+ * The DatagramPacketFilter that only accepts STUN messages.
+ */
+ private DatagramPacketFilter stunDatagramPacketFilter;
+
+ /**
+ * Creates a new ConnectivityCheckHandler setting
+ * parentAgent as the agent that will be used for retrieving
+ * information such as user fragments for example.
+ *
+ * @param parentAgent the Agent that is creating this instance.
+ */
+ public ConnectivityCheckHandler(Agent parentAgent)
+ {
+ stunStack.addRequestListener(this);
+ this.parentAgent = parentAgent;
+ }
+
+ public void startChecks(CheckList checkList)
+ {
+ for(CandidatePair pair : checkList)
+ {
+ startCheckForPair(pair);
+ }
+ }
+
+
+ private void startCheckForPair(CandidatePair pair)
+ {
+ //we don't need to do a canReach() verification here as it has been
+ //already verified during the gathering process.
+ DatagramSocket stunSocket = ((HostCandidate)pair.getLocalCandidate())
+ .getStunSocket(null);
+
+ Request request = MessageFactory.createBindingRequest();
+
+ //priority
+ PriorityAttribute priority = AttributeFactory.createPriorityAttribute(
+ pair.getLocalCandidate().computePriorityForType(
+ CandidateType.PEER_REFLEXIVE_CANDIDATE));
+
+ request.addAttribute(priority);
+
+ //controlling controlled
+ if (parentAgent.isControlling())
+ {
+ request.addAttribute(AttributeFactory
+ .createIceControllingAttribute(parentAgent
+ .getTieBreaker()));
+ }
+ else
+ {
+ request.addAttribute(AttributeFactory
+ .createIceControlledAttribute(parentAgent
+ .getTieBreaker()));
+ }
+
+ //credentials
+ UsernameAttribute unameAttr = AttributeFactory.createUsernameAttribute(
+ parentAgent.generateLocalUserName());
+
+ request.addAttribute(unameAttr);
+
+ //todo: do this in the stun stack so that we could do the
+ //calculation once the request is ready (we'd need the transaction id
+ //for example.
+ //todo: also implement SASL prepare
+ MessageIntegrityAttribute msgIntegrity
+ = AttributeFactory.createMessageIntegrityAttribute(
+ parentAgent.getLocalPassword().getBytes());
+
+
+ request.addAttribute(msgIntegrity);
+
+ TransactionID tran;
+
+ try
+ {
+ tran = stunStack.sendRequest(request,
+ pair.getRemoteCandidate().getTransportAddress(), stunSocket,
+ this);
+System.out.println("checking pair " + pair + " with tran=" + tran.toString());
+ }
+ catch (Exception exception)
+ {
+ logger.log( Level.INFO,
+ "Failed to send " + request + " through "
+ + stunSocket.getLocalSocketAddress(),
+ exception);
+ return;
+ }
+ }
+
+ public void processResponse(StunMessageEvent response)
+ {
+ }
+
+ public void processTimeout(StunTimeoutEvent event)
+ {
+ System.out.println("timeout event=" + event);
+ }
+
+ public void processUnreachable(StunFailureEvent event)
+ {
+ System.out.println("failure event=" + event);
+ }
+
+ public void requestReceived(StunMessageEvent evt)
+ {
+ Request request = (Request)evt.getMessage();
+
+ //check the user name
+ if(! checkUserName(request))
+ return;
+
+ //check message integrity.
+
+ Response response = MessageFactory.createBindingResponse(
+ request, evt.getRemoteAddress());
+ try
+ {
+ stunStack.sendResponse(evt.getTransactionID().getTransactionID(),
+ response, evt.getLocalAddress(), evt.getRemoteAddress());
+ }
+ catch (Exception e)
+ {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * Verifies whether request comes with the proper username and
+ * returns true if it does and false otherwise.
+ *
+ * @param request the Request that we'd like to check for a
+ * proper username.
+ *
+ * @return true if the request contains the proper user
+ * name and false otherwise.
+ */
+ public boolean checkUserName(Request request)
+ {
+ UsernameAttribute unameAttr
+ = (UsernameAttribute)request.getAttribute(Attribute.USERNAME);
+
+ if (unameAttr == null)
+ {
+ logger.log(Level.INFO, "Received a request without a USERNAME");
+ return false;
+ }
+
+ String username = new String(unameAttr.getUsername());
+ int colon = username.indexOf(":");
+ if( username.length() < 1
+ || colon < 1)
+ {
+ logger.log(Level.INFO, "Received a request with an improperly "
+ +"formatted username");
+ return false;
+ }
+
+ String lfrag = username.substring(0, colon);
+
+ if( !lfrag.equals(parentAgent.getLocalUfrag()))
+ {
+ logger.log(Level.INFO, "Remote peer using a wrong user name: "
+ + username);
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Verifies whether request comes with the proper
+ * MESSAGE-INTEGRITY attribute and returns true if it does
+ * and false otherwise.
+ *
+ * @param request the Request that we'd like to check for a
+ * proper MESSAGE-INTEGRITY attribute.
+ *
+ * @return true if the request contains the proper message
+ * integrity attribute and false otherwise.
+ */
+ public boolean checkMessageIntegrity(Request request)
+ {
+ MessageIntegrityAttribute msgIntegrityAttr = (MessageIntegrityAttribute)
+ request.getAttribute(Attribute.USERNAME);
+
+ if (msgIntegrityAttr == null)
+ {
+ logger.log(Level.INFO, "Received a request without a "
+ +"MESSAGE-INTEGRITY attribute");
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Implements the {@link CredentialsAuthority#getKey(String)} method in a
+ * way that would return this handler's parent agent password if
+ * username is either the local ufrag or the username that the
+ * agent's remote peer was expected to use.
+ *
+ * @param username the local ufrag that we should return a password for.
+ *
+ * @return this handler's parent agent local password if username
+ * equals the local ufrag and null otherwise.
+ */
+ public byte[] getKey(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
+ username = username.substring(0, colon);
+
+ if (username.equals(parentAgent.getLocalUfrag()))
+ return parentAgent.getLocalPassword().getBytes();
+ }
+ else
+ {
+ //caller gave us the entire username.
+ if (username.equals(parentAgent.generateRemoteUserName()))
+ return parentAgent.getLocalPassword().getBytes();
+ }
+
+ return null;
+ }
+}
diff --git a/src/org/ice4j/message/Message.java b/src/org/ice4j/message/Message.java
index 26fb52d..d1efb60 100644
--- a/src/org/ice4j/message/Message.java
+++ b/src/org/ice4j/message/Message.java
@@ -667,12 +667,26 @@ public abstract class Message
binMessage, offset, (char)(length - offset), //attribute
binMessage, (char)initialOffset,
(char)(offset - initialOffset)); // message head
+
+ if (att instanceof MessageIntegrityAttribute)
+ {
+ message
+ .validateMessageIntegrity((MessageIntegrityAttribute)att);
+ }
+
message.addAttribute(att);
offset += att.getDataLength() + Attribute.HEADER_LENGTH;
}
return message;
+ }
+ public boolean validateMessageIntegrity(MessageIntegrityAttribute msgInt,
+ byte[] message)
+ {
+ msgInt
+
+ return false;
}
/**
diff --git a/src/org/ice4j/security/CredentialsAuthority.java b/src/org/ice4j/security/CredentialsAuthority.java
new file mode 100644
index 0000000..b8e7b62
--- /dev/null
+++ b/src/org/ice4j/security/CredentialsAuthority.java
@@ -0,0 +1,32 @@
+/*
+ * 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;
+
+/**
+ * The {@link CredentialsAuthority} interface is implemented by applications
+ * in order to allow the stack to verify the integrity of incoming messages
+ * containing the MessageIntegrity attribute.
+ *
+ * @author Emil Ivov
+ */
+public interface CredentialsAuthority
+{
+ /**
+ * Returns the key (password) that corresponds to the specified username,
+ * an empty array if there was no password for that username or
+ * null if the username is not known to this
+ * CredentialsAuthority.
+ *
+ * @param username the user name whose credentials we'd like to obtain.
+ *
+ * @return the key (password) that corresponds to the specified username,
+ * an empty array if there was no password for that username or
+ * null if the username is not known to this
+ * CredentialsAuthority.
+ */
+ public byte[] getKey(String username);
+}
diff --git a/src/org/ice4j/security/CredentialsManager.java b/src/org/ice4j/security/CredentialsManager.java
new file mode 100644
index 0000000..2453393
--- /dev/null
+++ b/src/org/ice4j/security/CredentialsManager.java
@@ -0,0 +1,84 @@
+/*
+ * 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.util.*;
+import java.util.logging.*;
+
+/**
+ * The CredentialsManager allows an application to handle verification
+ * of incoming MessageIntegrityAttributes by registering a
+ * {@link CredentialsAuthority} implementation. The point of this mechanism
+ * is to allow use in both applications that would handle large numbers of
+ * possible users (such as STUN/TURN servers) or others that would only work
+ * with a few, like for example an ICE implementation.
+ *
+ * @todo just throwing a user name at the manager and expecting it to find
+ * an authority that knows about it may lead to ambiguities so we may need
+ * to add other parameters in here that would allow us to better select an
+ * authority.
+ *
+ * @author Emil Ivov
+ */
+public class CredentialsManager
+{
+ /**
+ * The list of CredentialsAuthoritys registered with this manager
+ * as being able to provide credentials.
+ */
+ private final List authorities =
+ new LinkedList();
+
+ /**
+ * Queries all currently registered {@link CredentialsAuthority}s for a
+ * password corresponding to username and returns the first
+ * non-null one.
+ *
+ * @param username the user name whose credentials we'd like to obtain.
+ *
+ * @return null if username was not known to neither of the
+ * currently registered CredentialsAuthoritys or a byte
+ * array containing the first non-null password that one of them
+ * returned.
+ */
+ public byte[] getKey(String username)
+ {
+ for (CredentialsAuthority auth : authorities)
+ {
+ byte[] passwd = auth.getKey(username);
+
+ if (passwd != null)
+ return passwd;
+ }
+
+ return null;
+ }
+
+ /**
+ * Adds authority to the list of {@link CredentialsAuthority}s
+ * registered with this manager.
+ *
+ * @param authority the {@link CredentialsAuthority} to add to this manager.
+ */
+ public void registerAuthority(CredentialsAuthority authority)
+ {
+ if(!authorities.contains(authority))
+ authorities.add(authority);
+ }
+
+ /**
+ * Removes authority from the list of {@link CredentialsAuthority}s
+ * registered with this manager.
+ *
+ * @param authority the {@link CredentialsAuthority} to remove from this
+ * manager.
+ */
+ public void unregisterAuthority(CredentialsAuthority authority)
+ {
+ authorities.remove(authority);
+ }
+}
diff --git a/src/org/ice4j/stack/StunStack.java b/src/org/ice4j/stack/StunStack.java
index 2b6e8df..b021973 100644
--- a/src/org/ice4j/stack/StunStack.java
+++ b/src/org/ice4j/stack/StunStack.java
@@ -12,7 +12,9 @@ import java.util.*;
import java.util.logging.*;
import org.ice4j.*;
+import org.ice4j.attribute.*;
import org.ice4j.message.*;
+import org.ice4j.security.*;
/**
* The entry point to the Stun4J stack. The class is used to start, stop and
@@ -38,6 +40,13 @@ public class StunStack
*/
public static final int DEFAULT_THREAD_POOL_SIZE = 3;
+ /**
+ * The {@link CredentialsManager} that we are using for retrieving
+ * passwords.
+ */
+ private static final CredentialsManager credentialsManager
+ = new CredentialsManager();
+
/**
* Our class logger.
*/
@@ -440,6 +449,18 @@ public class StunStack
}
}
+ /**
+ * Returns the {@link CredentialsManager} that this stack is using for
+ * verification of {@link MessageIntegrityAttribute}s.
+ *
+ * @return the {@link CredentialsManager} that this stack is using for
+ * verification of {@link MessageIntegrityAttribute}s.
+ */
+ public static CredentialsManager getCredentialsManager()
+ {
+ return credentialsManager;
+ }
+
/**
* Cancels all running transactions and prepares for garbage collection
*/