WCF и перекос часов - пользовательская конфигурация привязки игнорируется? - PullRequest
1 голос
/ 21 июня 2011

Наши клиенты сталкиваются с теми же проблемами перекоса часов, которые преследуют , поэтому многие другие люди.

Ответы на этих страницах и дальнейший поиск в сети очень помогли, но я столкнулся с другой проблемой.

При отладке на моем локальном компьютере я вижу, что свойства привязок установлены правильно. Но так как я не могу протестировать код локально (у меня есть только один такт), я должен опубликовать сервис на тестовом сервере. Тем не менее, когда я подключаюсь к услуге с искаженными часами, я все равно получаю MessageSecurityException s.

Моей первой мыслью было, что привязка изменяется после создания, но и я, и сотрудник в этом проекте подтвердили, что привязки создаются один раз, а не затрагиваются после.

Я, очевидно, делаю это неправильно [ТМ]. Я был бы очень признателен, если бы кто-то мог пролить свет на этот вопрос. Заранее спасибо.


Это код, который создает привязку:

WSHttpBinding binding = new WSHttpBinding();
binding.Security.Mode = SecurityMode.TransportWithMessageCredential;
binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;

// ... blah blah ...

// fix ongoing security
sbe.LocalClientSettings.DetectReplays = false;
sbe.LocalClientSettings.MaxClockSkew = TimeSpan.MaxValue;
sbe.LocalClientSettings.SessionKeyRenewalInterval = TimeSpan.MaxValue;

sbe.LocalServiceSettings.DetectReplays = false;
sbe.LocalServiceSettings.MaxClockSkew = TimeSpan.MaxValue;
sbe.LocalServiceSettings.SessionKeyRenewalInterval = TimeSpan.MaxValue;

// fix bootstrap security
SecureConversationSecurityTokenParameters sct = null;

if (sbe is SymmetricSecurityBindingElement)
{
    SecurityTokenParameters tokenParameters = 
((SymmetricSecurityBindingElement)sbe).ProtectionTokenParameters;
    if (tokenParameters is SecureConversationSecurityTokenParameters)
    {
        sct = tokenParameters as SecureConversationSecurityTokenParameters; 
    }
}
else if (sbe is TransportSecurityBindingElement)
{
    sct = sbe.EndpointSupportingTokenParameters
             .Endorsing
             .OfType<SecureConversationSecurityTokenParameters>()
             .FirstOrDefault();
}
else
{
    throw new ArgumentException("Binding has neiter a " +
       "SymmetricSecurityBindingElement nor " + 
       "TransportSecurityBindingElement");
}

SecurityBindingElement bootbe = sct.BootstrapSecurityBindingElement;

bootbe.LocalClientSettings.DetectReplays = false;
bootbe.LocalClientSettings.MaxClockSkew = TimeSpan.MaxValue;
bootbe.LocalClientSettings.SessionKeyRenewalInterval = TimeSpan.MaxValue;

bootbe.LocalServiceSettings.DetectReplays = false;
bootbe.LocalServiceSettings.MaxClockSkew = TimeSpan.MaxValue;
bootbe.LocalServiceSettings.SessionKeyRenewalInterval = TimeSpan.MaxValue;

Это стек вызовов исключения, которое я получаю в журнале трассировки службы:

System.ServiceModel.Security.MessageSecurityException, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

System.ServiceModel.Security.TransportSecurityProtocol.VerifyIncomingMessage(Message&amp; message, TimeSpan timeout)
System.ServiceModel.Security.SecurityProtocol.VerifyIncomingMessage(Message&amp; message, TimeSpan timeout, SecurityProtocolCorrelationState[] correlationStates)
System.ServiceModel.Channels.SecurityChannelListener`1.ServerSecurityChannel`1.VerifyIncomingMessage(Message&amp; message, TimeSpan timeout, SecurityProtocolCorrelationState[] correlationState)
System.ServiceModel.Channels.SecurityChannelListener`1.SecurityReplyChannel.ProcessReceivedRequest(RequestContext requestContext, TimeSpan timeout)
System.ServiceModel.Channels.SecurityChannelListener`1.ReceiveItemAndVerifySecurityAsyncResult`2.OnInnerReceiveDone()
System.ServiceModel.Channels.SecurityChannelListener`1.ReceiveItemAndVerifySecurityAsyncResult`2.InnerTryReceiveCompletedCallback(IAsyncResult result)
System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
System.Runtime.AsyncResult.Complete(Boolean completedSynchronously)
System.Runtime.InputQueue`1.AsyncQueueReader.Set(Item item)
System.Runtime.InputQueue`1.Dispatch()
System.Runtime.ActionItem.DefaultActionItem.Invoke()
System.Runtime.ActionItem.CallbackHelper.InvokeWithoutContext(Object state)
System.Runtime.IOThreadScheduler.ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
System.Runtime.Fx.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)

1 Ответ

1 голос
/ 14 ноября 2011

Вы должны получить MessageSecurityException, если ваше сообщение отклонено из-за того, что время на сервере и клиенте отличается более, чем на настройку наклона часов. Учитывая ваше описание, я думаю, что вы видите то, что ожидается.

Согласно Microsoft , причина, по которой MessageSecurityException возвращается вместо чего-то более конкретного, заключается в том, что

Исключения безопасности могут раскрыть некоторую очень чувствительную информацию и из-за к этому мы решили не подвергать никакие детали из уровня безопасности. Например, проблема с перекосом часов, о которой вы упоминали, когда разоблачить в вине исключения, предоставит злоумышленнику часы перекосить настройки сервиса и дает информацию для крафта более специфическая атака.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...