Completes support for automatically generating error responses

This commit is contained in:
emcho 2010-05-01 21:37:13 +00:00
parent 29c128ce74
commit 8c446d6f24
5 changed files with 116 additions and 204 deletions

View File

@ -138,13 +138,13 @@ public class AttributeFactory
* rfc3489.
*
* @return the newly created attribute.
* @throws StunException if errorCode is not a valid error code as defined
* by rfc3489
* @throws IllegalArgumentException if errorCode is not a valid error code
* as defined by rfc3489
*/
public static ErrorCodeAttribute createErrorCodeAttribute(
char errorCode,
String reasonPhrase)
throws StunException
throws IllegalArgumentException
{
ErrorCodeAttribute attribute = new ErrorCodeAttribute();

View File

@ -101,10 +101,9 @@ public class ErrorCodeAttribute extends Attribute
/**
* The reason phrase is meant for user consumption, and can
* be anything appropriate for the response code. The lengths of the
* reason phrases MUST be a multiple of 4 (measured in bytes).
* be anything appropriate for the response code.
*/
private String reasonPhrase = null;
private byte[] reasonPhrase = null;
/**
* Constructs a new ERROR-CODE attribute
@ -121,10 +120,10 @@ public class ErrorCodeAttribute extends Attribute
* code modulo 100, and its value MUST be between 0 and 99.
*
* @param errorCode the errorCode that this class encapsulates.
* @throws StunException if errorCode is not a valid error code.
* @throws IllegalArgumentException if errorCode is not a valid error code.
*/
public void setErrorCode(char errorCode)
throws StunException
throws IllegalArgumentException
{
setErrorClass((byte)(errorCode/100));
setErrorNumber((byte)(errorCode % 100));
@ -144,14 +143,15 @@ public class ErrorCodeAttribute extends Attribute
/**
* Sets this attribute's error number.
* @param errorNumber the error number to assign this attribute.
* @throws StunException if errorNumber is not a valid error number.
* @throws IllegalArgumentException if errorNumber is not a valid error
* number.
*/
public void setErrorNumber(byte errorNumber)
throws StunException
throws IllegalArgumentException
{
if(errorNumber < 0 || errorNumber > 99)
throw new StunException(StunException.ILLEGAL_ARGUMENT,
errorNumber + " is not a valid error number!");
throw new IllegalArgumentException(
errorNumber + " is not a valid error number!");
this.errorNumber = errorNumber;
}
@ -167,13 +167,13 @@ public class ErrorCodeAttribute extends Attribute
/**
* Sets this error's error class.
* @param errorClass this error's error class.
* @throws StunException if errorClass is not a valid error class.
* @throws IllegalArgumentException if errorClass is not a valid error class.
*/
public void setErrorClass(byte errorClass)
throws StunException
throws IllegalArgumentException
{
if(errorClass < 0 || errorClass > 99)
throw new StunException(StunException.ILLEGAL_ARGUMENT,
throw new IllegalArgumentException(
errorClass + " is not a valid error number!");
this.errorClass = errorClass;
}
@ -237,7 +237,7 @@ public class ErrorCodeAttribute extends Attribute
*/
public void setReasonPhrase(String reasonPhrase)
{
this.reasonPhrase = reasonPhrase;
this.reasonPhrase = reasonPhrase.getBytes();
}
/**
@ -249,7 +249,10 @@ public class ErrorCodeAttribute extends Attribute
*/
public String getReasonPhrase()
{
return this.reasonPhrase;
if(reasonPhrase == null)
return null;
return new String(reasonPhrase);
}
/**
@ -272,16 +275,8 @@ public class ErrorCodeAttribute extends Attribute
public char getDataLength()
{
char len = (char)( 4 //error code numbers
+ (char)(
reasonPhrase == null? 0
:reasonPhrase.length()*2
));
+ (char)(reasonPhrase == null? 0:reasonPhrase.length));
/*
* According to rfc 3489 The length of the
* reason phrases MUST be a multiple of 4 (measured in bytes)
*/
len += 4 - (len%4);
return len;
}
@ -291,7 +286,9 @@ public class ErrorCodeAttribute extends Attribute
*/
public byte[] encode()
{
byte binValue[] = new byte[HEADER_LENGTH + getDataLength()];
byte binValue[] = new byte[HEADER_LENGTH + getDataLength()
//add padding
+ (4 - getDataLength()%4)%4];
//Type
binValue[0] = (byte) (getAttributeType() >> 8);
@ -308,20 +305,8 @@ public class ErrorCodeAttribute extends Attribute
binValue[6] = getErrorClass();
binValue[7] = getErrorNumber();
int offset = 8;
char chars[] = reasonPhrase.toCharArray();
for (int i = 0; i < reasonPhrase.length(); i++, offset += 2) {
binValue[offset] = (byte)(chars[i]>>8);
binValue[offset+1] = (byte)(chars[i] & 0xFF);
}
//The lengths of the reason phrases MUST be a multiple of 4 (measured
//in bytes)
if( reasonPhrase.length()%4 != 0)
{
binValue[binValue.length - 2] = (byte) ( ( (int) ' ') >> 8);
binValue[binValue.length - 1] = (byte) ( ( (int) ' ') & 0x00FF);
}
if(reasonPhrase != null)
System.arraycopy(reasonPhrase, 0, binValue, 8, reasonPhrase.length);
return binValue;
}

View File

@ -313,6 +313,16 @@ public abstract class Message
return attributes.get(new Character(attributeType));
}
/**
* Returns a copy of all {@link Attribute}s in this {@link Message}.
*
* @return a copy of all {@link Attribute}s in this {@link Message}.
*/
public List<Attribute> getAttributes()
{
return new LinkedList<Attribute>(attributes.values());
}
/**
* Removes the specified attribute.
*
@ -776,112 +786,6 @@ public abstract class Message
return true;
}
/**
* 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.
*/
private boolean validateMessageIntegrity(MessageIntegrityAttribute msgInt,
byte[] message,
int offset,
int length)
{
//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;
}
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().getLocalKey(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;
}
/**
* Asserts the validity of the user name we've received in
* <tt>unameAttr</tt>.
*
* @param unameAttr the attribute that we need to validate.
*
* @return <tt>true</tt> if <tt>unameAttr</tt> contains a valid user name
* and <tt>false</tt> otherwise.
*/
private static boolean validateUsername(UsernameAttribute unameAttr)
{
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);
return StunStack.getInstance()
.getCredentialsManager().checkLocalUserName(lfrag);
}
/**
* Verify that the message has all obligatory attributes and throw an
* exception if this is not the case.

View File

@ -207,19 +207,18 @@ public class MessageFactory
* @param reasonPhrase a human readable description of the error
* @param unknownAttributes a char[] array containing the ids of one or more
* attributes that had not been recognized.
* @throws StunException INVALID_ARGUMENTS if one or more of the given
* parameters had an invalid value.
* @throws IllegalArgumentException INVALID_ARGUMENTS if one or more of the
* given parameters had an invalid value.
*
* @return a binding error response message containing an error code and a
* UNKNOWN-ATTRIBUTES header
*/
private static Response createBindingErrorResponse(char errorCode,
public static Response createBindingErrorResponse(char errorCode,
String reasonPhrase, char[] unknownAttributes)
throws StunException
throws IllegalArgumentException
{
Response bindingErrorResponse = new Response();
bindingErrorResponse
.setMessageType(Message.BINDING_ERROR_RESPONSE);
bindingErrorResponse.setMessageType(Message.BINDING_ERROR_RESPONSE);
// init attributes
UnknownAttributesAttribute unknownAttributesAttribute = null;
@ -290,14 +289,12 @@ public class MessageFactory
*
* @param errorCode the error code to encapsulate in this message
* @param reasonPhrase a human readable description of the error.
* @throws StunException INVALID_ARGUMENTS if one or more of the given
* parameters had an invalid value.
*
* @return a binding error response message containing an error code and a
* UNKNOWN-ATTRIBUTES header
*/
public static Response createBindingErrorResponse(char errorCode,
String reasonPhrase) throws StunException
String reasonPhrase)
{
return createBindingErrorResponse(errorCode, reasonPhrase, null);
}

View File

@ -526,7 +526,15 @@ public class StunStack
}
//validate attributes that need validation.
validateRequestAttributes((Request)msg, event.getRawMessage());
try
{
validateRequestAttributes((Request)msg, event.getRawMessage());
}
catch(Exception exc)
{
//validation failed. get lost.
return;
}
eventDispatcher.fireMessageEvent(event);
@ -602,21 +610,32 @@ public class StunStack
* <tt>attribute</tt> that caused us to discard the whole message (e.g. an
* invalid checksum
* or username)
* @throws StunException if we fail while sending an error response.
* @throws IOException if we fail while sending an error response.
*/
private void validateRequestAttributes(Request request,
RawMessage rawMessage)
throws IllegalArgumentException
throws IllegalArgumentException, StunException, IOException
{
///HANDLE OPTIONAL ATTRIBUTES!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//assert valid username
UsernameAttribute unameAttr = (UsernameAttribute)request
.getAttribute(Attribute.USERNAME);
String username;
if (unameAttr != null)
{
username = new String(unameAttr.getUsername());
if (!validateUsername( unameAttr))
{
Response error = MessageFactory.createBindingErrorResponse(
ErrorCodeAttribute.UNAUTHORIZED,
"unknown user " + username);
sendResponse(request.getTransactionID(), error,
rawMessage.getLocalAddress(),
rawMessage.getRemoteAddress());
throw new IllegalArgumentException(
"Non-recognized username: "
+ new String(unameAttr.getUsername()));
@ -632,65 +651,72 @@ public class StunStack
//we should complain if we have msg integrity and no username.
if (unameAttr == null)
{
Response error = MessageFactory.createBindingErrorResponse(
ErrorCodeAttribute.BAD_REQUEST,
"missing username");
sendResponse(request.getTransactionID(), error,
rawMessage.getLocalAddress(),
rawMessage.getRemoteAddress());
throw new IllegalArgumentException(
"Missing USERNAME in the presence of MESSAGE-INTEGRITY: ");
}
if (!validateMessageIntegrity(msgIntAttr,
new String(unameAttr.getUsername())
,rawMessage.getBytes(), 0))
new String(unameAttr.getUsername()),
rawMessage.getBytes(), 0))
{
Response error = MessageFactory.createBindingErrorResponse(
ErrorCodeAttribute.UNAUTHORIZED,
"Wrong MESSAGE-INTEGRITY value");
sendResponse(request.getTransactionID(), error,
rawMessage.getLocalAddress(),
rawMessage.getRemoteAddress());
throw new IllegalArgumentException(
"Wrong MESSAGE-INTEGRITY value.");
}
}
}
/**
* Recalculates the FINGERPRINT CRC32 checksum of the <tt>message</tt>
* array so that we could compare it with the value brought by the
* {@link FingerprintAttribute}.
*
* @param fingerprint the attribute that we need to validate.
* @param message the message whose CRC32 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 CRC32
* would need to be calculated over.
*
* @return <tt>true</tt> if <tt>FINGERPRINT</tt> contains a valid CRC32
* value and <tt>false</tt> otherwise.
*/
private static boolean validateFingerprint(FingerprintAttribute fingerprint,
byte[] message,
int offset,
int length)
{
byte[] incomingCrcBytes = fingerprint.getChecksum();
//now check whether the CRC really is what it's supposed to be.
//re calculate the check sum
byte[] realCrcBytes = FingerprintAttribute.calculateXorCRC32(
message, offset, length);
//CRC validation.
if ( ! Arrays.equals(incomingCrcBytes, realCrcBytes))
else
{
if (logger.isLoggable(Level.FINE))
{
logger.fine(
"An incoming message arrived with a wrong FINGERPRINT "
+"attribute value. "
+"CRC Was:" + Arrays.toString(incomingCrcBytes)
+ ". Should have been:" + Arrays.toString(realCrcBytes)
+". Will ignore.");
}
// no message integrity
Response error = MessageFactory.createBindingErrorResponse(
ErrorCodeAttribute.UNAUTHORIZED,
"Missing MESSAGE-INTEGRITY.");
return false;
sendResponse(request.getTransactionID(), error,
rawMessage.getLocalAddress(),
rawMessage.getRemoteAddress());
throw new IllegalArgumentException(
"Missing MESSAGE-INTEGRITY.");
}
return true;
//look for unknown attributes.
List<Attribute> allAttributes = request.getAttributes();
StringBuffer sBuff = new StringBuffer();
for(Attribute attr : allAttributes)
{
if(attr instanceof OptionalAttribute
&& attr.getAttributeType()
< Attribute.UNKNOWN_OPTIONAL_ATTRIBUTE)
sBuff.append(attr.getAttributeType());
}
if (sBuff.length() > 0)
{
Response error = MessageFactory.createBindingErrorResponse(
ErrorCodeAttribute.UNKNOWN_ATTRIBUTE,
"missing username", sBuff.toString().toCharArray());
sendResponse(request.getTransactionID(), error,
rawMessage.getLocalAddress(),
rawMessage.getRemoteAddress());
throw new IllegalArgumentException(
"Missing MESSAGE-INTEGRITY.");
}
}
/**