diff --git a/src/org/ice4j/attribute/MessageIntegrityAttribute.java b/src/org/ice4j/attribute/MessageIntegrityAttribute.java
index bf77b88..cfafef8 100644
--- a/src/org/ice4j/attribute/MessageIntegrityAttribute.java
+++ b/src/org/ice4j/attribute/MessageIntegrityAttribute.java
@@ -124,6 +124,16 @@ public class MessageIntegrityAttribute
this.key = key;
}
+ /**
+ * Returns the HMAC-SHA1 value stored in this attribute.
+ *
+ * @return the HMAC-SHA1 value stored in this attribute.
+ */
+ public byte[] getHmacSha1Content()
+ {
+ return hmacSha1Content;
+ }
+
/**
* Encodes message using key and the HMAC-SHA1 algorithm
* as per RFC 2104 and returns the resulting byte array. This is a utility
@@ -132,6 +142,9 @@ public class MessageIntegrityAttribute
*
* @param message the STUN message that the resulting content will need to
* travel in.
+ * @param offset the index where data starts in message.
+ * @param length the length of the data in message that the method
+ * should consider.
* @param key the key that we should be using for the encoding (which
* depends on whether we are using short or long term credentials).
*
@@ -140,7 +153,10 @@ public class MessageIntegrityAttribute
*
* @throws IllegalArgumentException if the encoding fails for some reason.
*/
- public static byte[] createHmacSha1(byte[] message, byte[] key)
+ public static byte[] calculateHmacSha1(byte[] message,
+ int offset,
+ int length,
+ byte[] key)
throws IllegalArgumentException
{
byte[] hmac;
@@ -155,7 +171,14 @@ public class MessageIntegrityAttribute
mac.init(signingKey);
// compute the hmac on input data bytes
- hmac = mac.doFinal(message);
+ byte[] macInput = new byte[length];
+
+ //doFinal seems incapable to only work with a part of an array
+ //so we'd need to create an array that only contains what we
+ //actually need to work with.
+ System.arraycopy(message, offset, macInput, 0, length);
+
+ hmac = mac.doFinal(macInput);
}
catch (Exception exc)
{
@@ -266,7 +289,8 @@ public class MessageIntegrityAttribute
binValue[3] = (byte)(getDataLength()&0x00FF);
//now calculate the HMAC-SHA1
- this.hmacSha1Content = createHmacSha1(content, this.key);
+ this.hmacSha1Content = calculateHmacSha1(
+ content, offset, length, this.key);
//username
System.arraycopy(hmacSha1Content, 0, binValue, 4, getDataLength());
diff --git a/src/org/ice4j/ice/ConnectivityCheckHandler.java b/src/org/ice4j/ice/ConnectivityCheckHandler.java
index 60c9c5b..7cf9b5c 100644
--- a/src/org/ice4j/ice/ConnectivityCheckHandler.java
+++ b/src/org/ice4j/ice/ConnectivityCheckHandler.java
@@ -6,6 +6,7 @@
*/
package org.ice4j.ice;
+import java.io.*;
import java.net.*;
import java.util.logging.*;
@@ -55,8 +56,9 @@ public class ConnectivityCheckHandler
*/
public ConnectivityCheckHandler(Agent parentAgent)
{
- stunStack.addRequestListener(this);
this.parentAgent = parentAgent;
+ stunStack.addRequestListener(this);
+ stunStack.getCredentialsManager().registerAuthority(this);
}
public void startChecks(CheckList checkList)
@@ -110,7 +112,7 @@ public class ConnectivityCheckHandler
//todo: also implement SASL prepare
MessageIntegrityAttribute msgIntegrity
= AttributeFactory.createMessageIntegrityAttribute(
- parentAgent.getLocalPassword().getBytes());
+ parentAgent.getRemotePassword().getBytes());
request.addAttribute(msgIntegrity);
@@ -189,7 +191,10 @@ System.out.println("checking pair " + pair + " with tran=" + tran.toString());
if (unameAttr == null)
{
- logger.log(Level.INFO, "Received a request without a USERNAME");
+ if(logger.isLoggable(Level.FINE))
+ {
+ logger.log(Level.FINE, "Received a request without a USERNAME");
+ }
return false;
}
@@ -198,8 +203,11 @@ System.out.println("checking pair " + pair + " with tran=" + tran.toString());
if( username.length() < 1
|| colon < 1)
{
- logger.log(Level.INFO, "Received a request with an improperly "
+ if(logger.isLoggable(Level.FINE))
+ {
+ logger.log(Level.FINE, "Received a request with an improperly "
+"formatted username");
+ }
return false;
}
@@ -207,34 +215,11 @@ System.out.println("checking pair " + pair + " with tran=" + tran.toString());
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");
+ if(logger.isLoggable(Level.FINE))
+ {
+ logger.log(Level.FINE, "Remote peer using a wrong user name: "
+ + username);
+ }
return false;
}
@@ -257,11 +242,9 @@ System.out.println("checking pair " + pair + " with tran=" + tran.toString());
//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
- username = username.substring(0, colon);
-
if (username.equals(parentAgent.getLocalUfrag()))
return parentAgent.getLocalPassword().getBytes();
}
diff --git a/src/org/ice4j/message/Message.java b/src/org/ice4j/message/Message.java
index d1efb60..bb3d5c8 100644
--- a/src/org/ice4j/message/Message.java
+++ b/src/org/ice4j/message/Message.java
@@ -7,6 +7,7 @@
package org.ice4j.message;
import java.util.*;
+import java.util.logging.*;
import org.ice4j.*;
import org.ice4j.attribute.*;
@@ -26,6 +27,13 @@ import sun.tools.tree.*;
*/
public abstract class Message
{
+ /**
+ * The Logger used by the Message
+ * class and its instances for logging output.
+ */
+ private static final Logger logger = Logger.getLogger(Message.class
+ .getName());
+
/* general declaration */
public static final char STUN_REQUEST = 0x0000;
public static final char STUN_INDICATION = 0x0010;
@@ -616,6 +624,7 @@ public abstract class Message
public static Message decode(byte binMessage[], char offset, char arrayLen)
throws StunException
{
+ int originalOffset = offset;
arrayLen = (char)Math.min(binMessage.length, arrayLen);
char initialOffset = offset;
@@ -644,7 +653,8 @@ public abstract class Message
message.setMessageType(messageType);
- int length = (char)((binMessage[offset++]<<8) | (binMessage[offset++]&0xFF));
+ int length = (char)((binMessage[offset++] << 8)
+ | (binMessage[offset++] & 0xFF));
/* copy the cookie */
byte cookie[] = new byte[4];
@@ -670,23 +680,94 @@ public abstract class Message
if (att instanceof MessageIntegrityAttribute)
{
- message
- .validateMessageIntegrity((MessageIntegrityAttribute)att);
+ if (!message.validateMessageIntegrity(
+ (MessageIntegrityAttribute)att,
+ binMessage, originalOffset, offset))
+ {
+ throw new StunException(StunException.ILLEGAL_ARGUMENT,
+ "Wrong value in MESSAGE-INTEGRITY");
+ }
+
}
message.addAttribute(att);
offset += att.getDataLength() + Attribute.HEADER_LENGTH;
}
-
return message;
}
+ /**
+ * 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.
+ */
public boolean validateMessageIntegrity(MessageIntegrityAttribute msgInt,
- byte[] message)
+ byte[] message,
+ int offset,
+ int length)
{
- msgInt
+ //first get a password for the username specified with this message.
+ UsernameAttribute unameAttr
+ = (UsernameAttribute)getAttribute(Attribute.USERNAME);
- return false;
+ 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().getKey(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;
}
/**
diff --git a/src/org/ice4j/stack/EventDispatcher.java b/src/org/ice4j/stack/EventDispatcher.java
index 49aaf25..66f7912 100644
--- a/src/org/ice4j/stack/EventDispatcher.java
+++ b/src/org/ice4j/stack/EventDispatcher.java
@@ -130,18 +130,19 @@ public class EventDispatcher
*/
public void fireMessageEvent(StunMessageEvent evt)
{
+
TransportAddress localAddr = evt.getLocalAddress();
+ List listenersCopy = null;
+
synchronized(requestListeners)
{
- List listenersCopy = null;
- synchronized(requestListeners)
- {
- listenersCopy
- = new ArrayList(requestListeners);
- }
+ listenersCopy
+ = new ArrayList(requestListeners);
+ }
- for (RequestListener target : listenersCopy)
- target.requestReceived(evt);
+ for (RequestListener target : listenersCopy)
+ {
+ target.requestReceived(evt);
}
synchronized(requestListenersChildren)
diff --git a/src/org/ice4j/stack/MessageProcessor.java b/src/org/ice4j/stack/MessageProcessor.java
index d0fd318..561dc29 100644
--- a/src/org/ice4j/stack/MessageProcessor.java
+++ b/src/org/ice4j/stack/MessageProcessor.java
@@ -139,6 +139,7 @@ class MessageProcessor
rawMessage.getLocalAddress(),
stunMessage,
rawMessage.getRemoteAddress());
+
messageHandler.handleMessageEvent(stunMessageEvent);
}
}
diff --git a/src/org/ice4j/stack/StunServerTransaction.java b/src/org/ice4j/stack/StunServerTransaction.java
index 390666e..93ba862 100644
--- a/src/org/ice4j/stack/StunServerTransaction.java
+++ b/src/org/ice4j/stack/StunServerTransaction.java
@@ -206,8 +206,8 @@ class StunServerTransaction
return;
stackCallback.getNetAccessManager().sendMessage(response,
- localSendingAddress,
- responseDestination);
+ localSendingAddress,
+ responseDestination);
}
/**
diff --git a/src/org/ice4j/stack/StunStack.java b/src/org/ice4j/stack/StunStack.java
index b021973..2abd926 100644
--- a/src/org/ice4j/stack/StunStack.java
+++ b/src/org/ice4j/stack/StunStack.java
@@ -44,7 +44,7 @@ public class StunStack
* The {@link CredentialsManager} that we are using for retrieving
* passwords.
*/
- private static final CredentialsManager credentialsManager
+ private final CredentialsManager credentialsManager
= new CredentialsManager();
/**
@@ -426,6 +426,7 @@ public class StunStack
}
eventDispatcher.fireMessageEvent(event);
+
}
//response
else if(msg instanceof Response)
@@ -456,7 +457,7 @@ public class StunStack
* @return the {@link CredentialsManager} that this stack is using for
* verification of {@link MessageIntegrityAttribute}s.
*/
- public static CredentialsManager getCredentialsManager()
+ public CredentialsManager getCredentialsManager()
{
return credentialsManager;
}
diff --git a/src/org/ice4j/util/Ice4jLogFormatter.java b/src/org/ice4j/util/Ice4jLogFormatter.java
new file mode 100644
index 0000000..cfd66f9
--- /dev/null
+++ b/src/org/ice4j/util/Ice4jLogFormatter.java
@@ -0,0 +1,148 @@
+/*
+ * 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.util;
+
+import java.io.*;
+import java.util.logging.*;
+import java.util.*;
+import java.text.*;
+
+/**
+ * Print a brief summary of the LogRecord in a human readable. The summary will
+ * typically be on a single line (unless it's too long :) ... what I meant to
+ * say is that we don't add any line breaks).
+ *
+ * @author Emil Ivov (originally wrote it for SIP Communicator)
+ */
+
+public class Ice4jLogFormatter
+ extends java.util.logging.Formatter
+{
+ static long startTime = System.currentTimeMillis();
+
+ private static String lineSeparator = System.getProperty("line.separator");
+ private static DecimalFormat twoDigFmt = new DecimalFormat("00");
+ private static DecimalFormat threeDigFmt = new DecimalFormat("000");
+
+ /**
+ * Format the given LogRecord.
+ * @param record the log record to be formatted.
+ * @return a formatted log record
+ */
+ public synchronized String format(LogRecord record)
+ {
+ StringBuffer sb = new StringBuffer();
+
+ //current time
+ Calendar cal = Calendar.getInstance();
+ int hour = cal.get(Calendar.HOUR_OF_DAY);
+ int minutes = cal.get(Calendar.MINUTE);
+ int seconds = cal.get(Calendar.SECOND);
+ int millis = cal.get(Calendar.MILLISECOND);
+
+ sb.append(twoDigFmt.format(hour)).append(':');
+ sb.append(twoDigFmt.format(minutes)).append(':');
+ sb.append(twoDigFmt.format(seconds)).append('.');
+ sb.append(threeDigFmt.format(millis)).append(' ');
+
+ //log level
+ sb.append(record.getLevel().getLocalizedName());
+ sb.append(": ");
+
+ //caller method
+ int lineNumber = inferCaller(record);
+ String loggerName = record.getLoggerName();
+
+ if(loggerName == null)
+ loggerName = record.getSourceClassName();
+
+ if(loggerName.startsWith("net.java.sip.communicator."))
+ {
+ sb.append(loggerName.substring("net.java.sip.communicator."
+ .length()));
+ }
+ else
+ sb.append(record.getLoggerName());
+
+ if (record.getSourceMethodName() != null)
+ {
+ sb.append(".");
+ sb.append(record.getSourceMethodName());
+
+ //include the line number if we have it.
+ if(lineNumber != -1)
+ sb.append("().").append(Integer.toString(lineNumber));
+ else
+ sb.append("()");
+ }
+ sb.append(" ");
+ sb.append(record.getMessage());
+ sb.append(lineSeparator);
+ if (record.getThrown() != null)
+ {
+ try
+ {
+ StringWriter sw = new StringWriter();
+ PrintWriter pw = new PrintWriter(sw);
+ record.getThrown().printStackTrace(pw);
+ pw.close();
+ sb.append(sw.toString());
+ }
+ catch (Exception ex)
+ {
+ }
+ }
+ return sb.toString();
+ }
+
+ /**
+ * Try to extract the name of the class and method that called the current
+ * log statement.
+ *
+ * @param record the logrecord where class and method name should be stored.
+ *
+ * @return the line number that the call was made from in the caller.
+ */
+ private int inferCaller(LogRecord record)
+ {
+ // Get the stack trace.
+ StackTraceElement stack[] = (new Throwable()).getStackTrace();
+
+ //the line number that the caller made the call from
+ int lineNumber = -1;
+
+ // First, search back to a method in the SIP Communicator Logger class.
+ int ix = 0;
+ while (ix < stack.length)
+ {
+ StackTraceElement frame = stack[ix];
+ String cname = frame.getClassName();
+ if (cname.equals("net.java.sip.communicator.util.Logger"))
+ {
+ break;
+ }
+ ix++;
+ }
+ // Now search for the first frame before the SIP Communicator Logger class.
+ while (ix < stack.length)
+ {
+ StackTraceElement frame = stack[ix];
+ lineNumber=stack[ix].getLineNumber();
+ String cname = frame.getClassName();
+ if (!cname.equals("net.java.sip.communicator.util.Logger"))
+ {
+ // We've found the relevant frame.
+ record.setSourceClassName(cname);
+ record.setSourceMethodName(frame.getMethodName());
+ break;
+ }
+ ix++;
+ }
+
+ return lineNumber;
+ }
+}