Fixes logging configuration

This commit is contained in:
emcho 2010-04-26 21:33:21 +00:00
parent 9044d7b348
commit 1c94ca7d3a
8 changed files with 296 additions and 57 deletions

View File

@ -124,6 +124,16 @@ public class MessageIntegrityAttribute
this.key = key; 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 <tt>message</tt> using <tt>key</tt> and the HMAC-SHA1 algorithm * Encodes <tt>message</tt> using <tt>key</tt> and the HMAC-SHA1 algorithm
* as per RFC 2104 and returns the resulting byte array. This is a utility * 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 * @param message the STUN message that the resulting content will need to
* travel in. * travel in.
* @param offset the index where data starts in <tt>message</tt>.
* @param length the length of the data in <tt>message</tt> that the method
* should consider.
* @param key the key that we should be using for the encoding (which * @param key the key that we should be using for the encoding (which
* depends on whether we are using short or long term credentials). * 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. * @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 throws IllegalArgumentException
{ {
byte[] hmac; byte[] hmac;
@ -155,7 +171,14 @@ public class MessageIntegrityAttribute
mac.init(signingKey); mac.init(signingKey);
// compute the hmac on input data bytes // 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) catch (Exception exc)
{ {
@ -266,7 +289,8 @@ public class MessageIntegrityAttribute
binValue[3] = (byte)(getDataLength()&0x00FF); binValue[3] = (byte)(getDataLength()&0x00FF);
//now calculate the HMAC-SHA1 //now calculate the HMAC-SHA1
this.hmacSha1Content = createHmacSha1(content, this.key); this.hmacSha1Content = calculateHmacSha1(
content, offset, length, this.key);
//username //username
System.arraycopy(hmacSha1Content, 0, binValue, 4, getDataLength()); System.arraycopy(hmacSha1Content, 0, binValue, 4, getDataLength());

View File

@ -6,6 +6,7 @@
*/ */
package org.ice4j.ice; package org.ice4j.ice;
import java.io.*;
import java.net.*; import java.net.*;
import java.util.logging.*; import java.util.logging.*;
@ -55,8 +56,9 @@ public class ConnectivityCheckHandler
*/ */
public ConnectivityCheckHandler(Agent parentAgent) public ConnectivityCheckHandler(Agent parentAgent)
{ {
stunStack.addRequestListener(this);
this.parentAgent = parentAgent; this.parentAgent = parentAgent;
stunStack.addRequestListener(this);
stunStack.getCredentialsManager().registerAuthority(this);
} }
public void startChecks(CheckList checkList) public void startChecks(CheckList checkList)
@ -110,7 +112,7 @@ public class ConnectivityCheckHandler
//todo: also implement SASL prepare //todo: also implement SASL prepare
MessageIntegrityAttribute msgIntegrity MessageIntegrityAttribute msgIntegrity
= AttributeFactory.createMessageIntegrityAttribute( = AttributeFactory.createMessageIntegrityAttribute(
parentAgent.getLocalPassword().getBytes()); parentAgent.getRemotePassword().getBytes());
request.addAttribute(msgIntegrity); request.addAttribute(msgIntegrity);
@ -189,7 +191,10 @@ System.out.println("checking pair " + pair + " with tran=" + tran.toString());
if (unameAttr == null) 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; return false;
} }
@ -198,8 +203,11 @@ System.out.println("checking pair " + pair + " with tran=" + tran.toString());
if( username.length() < 1 if( username.length() < 1
|| colon < 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"); +"formatted username");
}
return false; return false;
} }
@ -207,34 +215,11 @@ System.out.println("checking pair " + pair + " with tran=" + tran.toString());
if( !lfrag.equals(parentAgent.getLocalUfrag())) if( !lfrag.equals(parentAgent.getLocalUfrag()))
{ {
logger.log(Level.INFO, "Remote peer using a wrong user name: " if(logger.isLoggable(Level.FINE))
{
logger.log(Level.FINE, "Remote peer using a wrong user name: "
+ username); + 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 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 //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
username = username.substring(0, colon);
if (username.equals(parentAgent.getLocalUfrag())) if (username.equals(parentAgent.getLocalUfrag()))
return parentAgent.getLocalPassword().getBytes(); return parentAgent.getLocalPassword().getBytes();
} }

View File

@ -7,6 +7,7 @@
package org.ice4j.message; package org.ice4j.message;
import java.util.*; import java.util.*;
import java.util.logging.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.attribute.*; import org.ice4j.attribute.*;
@ -26,6 +27,13 @@ import sun.tools.tree.*;
*/ */
public abstract class Message public abstract class Message
{ {
/**
* The <tt>Logger</tt> used by the <tt>Message</tt>
* class and its instances for logging output.
*/
private static final Logger logger = Logger.getLogger(Message.class
.getName());
/* general declaration */ /* general declaration */
public static final char STUN_REQUEST = 0x0000; public static final char STUN_REQUEST = 0x0000;
public static final char STUN_INDICATION = 0x0010; 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) public static Message decode(byte binMessage[], char offset, char arrayLen)
throws StunException throws StunException
{ {
int originalOffset = offset;
arrayLen = (char)Math.min(binMessage.length, arrayLen); arrayLen = (char)Math.min(binMessage.length, arrayLen);
char initialOffset = offset; char initialOffset = offset;
@ -644,7 +653,8 @@ public abstract class Message
message.setMessageType(messageType); message.setMessageType(messageType);
int length = (char)((binMessage[offset++]<<8) | (binMessage[offset++]&0xFF)); int length = (char)((binMessage[offset++] << 8)
| (binMessage[offset++] & 0xFF));
/* copy the cookie */ /* copy the cookie */
byte cookie[] = new byte[4]; byte cookie[] = new byte[4];
@ -670,25 +680,96 @@ public abstract class Message
if (att instanceof MessageIntegrityAttribute) if (att instanceof MessageIntegrityAttribute)
{ {
message if (!message.validateMessageIntegrity(
.validateMessageIntegrity((MessageIntegrityAttribute)att); (MessageIntegrityAttribute)att,
binMessage, originalOffset, offset))
{
throw new StunException(StunException.ILLEGAL_ARGUMENT,
"Wrong value in MESSAGE-INTEGRITY");
}
} }
message.addAttribute(att); message.addAttribute(att);
offset += att.getDataLength() + Attribute.HEADER_LENGTH; offset += att.getDataLength() + Attribute.HEADER_LENGTH;
} }
return message; return message;
} }
/**
* Recalculates the HMAC-SHA1 signature of the <tt>message</tt> 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 <tt>message</tt> where data starts.
* @param length the number of bytes in <tt>message</tt> that the SHA1 would
* need to be calculated over.
*
* @return <tt>true</tt> if <tt>msgInt</tt> contains a valid SHA1 value and
* <tt>false</tt> otherwise.
*/
public boolean validateMessageIntegrity(MessageIntegrityAttribute msgInt, 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);
if (unameAttr == null)
{
logger.info( "Received a message containing a "
+" MESSAGE-INTEGRITY attribute and no USERNAME");
return false; 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;
}
/** /**
* Verify that the message has all obligatory attributes and throw an * Verify that the message has all obligatory attributes and throw an
* exception if this is not the case. * exception if this is not the case.

View File

@ -130,10 +130,10 @@ public class EventDispatcher
*/ */
public void fireMessageEvent(StunMessageEvent evt) public void fireMessageEvent(StunMessageEvent evt)
{ {
TransportAddress localAddr = evt.getLocalAddress(); TransportAddress localAddr = evt.getLocalAddress();
synchronized(requestListeners)
{
List<RequestListener> listenersCopy = null; List<RequestListener> listenersCopy = null;
synchronized(requestListeners) synchronized(requestListeners)
{ {
listenersCopy listenersCopy
@ -141,6 +141,7 @@ public class EventDispatcher
} }
for (RequestListener target : listenersCopy) for (RequestListener target : listenersCopy)
{
target.requestReceived(evt); target.requestReceived(evt);
} }

View File

@ -139,6 +139,7 @@ class MessageProcessor
rawMessage.getLocalAddress(), rawMessage.getLocalAddress(),
stunMessage, stunMessage,
rawMessage.getRemoteAddress()); rawMessage.getRemoteAddress());
messageHandler.handleMessageEvent(stunMessageEvent); messageHandler.handleMessageEvent(stunMessageEvent);
} }
} }

View File

@ -44,7 +44,7 @@ public class StunStack
* The {@link CredentialsManager} that we are using for retrieving * The {@link CredentialsManager} that we are using for retrieving
* passwords. * passwords.
*/ */
private static final CredentialsManager credentialsManager private final CredentialsManager credentialsManager
= new CredentialsManager(); = new CredentialsManager();
/** /**
@ -426,6 +426,7 @@ public class StunStack
} }
eventDispatcher.fireMessageEvent(event); eventDispatcher.fireMessageEvent(event);
} }
//response //response
else if(msg instanceof Response) else if(msg instanceof Response)
@ -456,7 +457,7 @@ public class StunStack
* @return the {@link CredentialsManager} that this stack is using for * @return the {@link CredentialsManager} that this stack is using for
* verification of {@link MessageIntegrityAttribute}s. * verification of {@link MessageIntegrityAttribute}s.
*/ */
public static CredentialsManager getCredentialsManager() public CredentialsManager getCredentialsManager()
{ {
return credentialsManager; return credentialsManager;
} }

View File

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