Adds support for verification of incoming MESSAGE-INTEGRITY attributes

This commit is contained in:
emcho 2010-04-26 21:32:47 +00:00
parent ca1794fed7
commit b9a8f624d0
6 changed files with 431 additions and 3 deletions

View File

@ -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 <tt>Agent</tt> to use
* Returns the user name that we should tell a peer <tt>Agent</tt> 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());

View File

@ -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 <tt>Logger</tt> used by the <tt>ConnectivityCheckClient</tt>
* 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 <tt>DatagramPacketFilter</tt> that only accepts STUN messages.
*/
private DatagramPacketFilter stunDatagramPacketFilter;
/**
* Creates a new <tt>ConnectivityCheckHandler</tt> setting
* <tt>parentAgent</tt> as the agent that will be used for retrieving
* information such as user fragments for example.
*
* @param parentAgent the <tt>Agent</tt> 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 <tt>request</tt> comes with the proper username and
* returns <tt>true</tt> if it does and <tt>false</tt> otherwise.
*
* @param request the <tt>Request</tt> that we'd like to check for a
* proper username.
*
* @return <tt>true</tt> if the <tt>request</tt> 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 <tt>request</tt> comes with the proper
* <tt>MESSAGE-INTEGRITY</tt> attribute and returns <tt>true</tt> if it does
* and <tt>false</tt> otherwise.
*
* @param request the <tt>Request</tt> that we'd like to check for a
* proper <tt>MESSAGE-INTEGRITY</tt> attribute.
*
* @return <tt>true</tt> if the <tt>request</tt> 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
* <tt>username</tt> 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 <tt>username</tt>
* equals the local ufrag and <tt>null</tt> 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;
}
}

View File

@ -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;
}
/**

View File

@ -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 <tt>MessageIntegrity</tt> 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
* <tt>null</tt> if the username is not known to this
* <tt>CredentialsAuthority</tt>.
*
* @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
* <tt>null</tt> if the username is not known to this
* <tt>CredentialsAuthority</tt>.
*/
public byte[] getKey(String username);
}

View File

@ -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 <tt>CredentialsManager</tt> allows an application to handle verification
* of incoming <tt>MessageIntegrityAttribute</tt>s 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 <tt>CredentialsAuthority</tt>s registered with this manager
* as being able to provide credentials.
*/
private final List<CredentialsAuthority> authorities =
new LinkedList<CredentialsAuthority>();
/**
* Queries all currently registered {@link CredentialsAuthority}s for a
* password corresponding to <tt>username</tt> and returns the first
* non-<tt>null</tt> one.
*
* @param username the user name whose credentials we'd like to obtain.
*
* @return <tt>null</tt> if username was not known to neither of the
* currently registered <tt>CredentialsAuthority</tt>s or a <tt>byte</tt>
* array containing the first non-<tt>null</tt> 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 <tt>authority</tt> 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 <tt>authority</tt> 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);
}
}

View File

@ -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
*/