Faultstring a security error was encountered when verifying the message

Hi! zeep 4.0.0. I'm testing zeep against http://www.sigecweb.beniculturali.it/webServiceBrowsingCards?wsdl. It has a security policy. Note: download the wdsl locally because of a wrong address ...

Hi!

zeep 4.0.0.

I’m testing zeep against http://www.sigecweb.beniculturali.it/webServiceBrowsingCards?wsdl. It has a security policy.
Note: download the wdsl locally because of a wrong address inside, replace 10.96.1.85:8180 with sigecweb.beniculturali.it (so you’ve:

    <port binding="tns:WSBrowsingItemsBinding" name="WSBrowsingItemsPort">
      <soap:address location="http://sigecweb.beniculturali.it/webServiceBrowsingCards"/>
    </port>

This is the code I’m using:

from zeep import Client
from zeep.cache import SqliteCache
from zeep.transports import Transport
from zeep.wsse.username import UsernameToken
from zeep.wsse.signature import Signature
import datetime
from zeep.plugins import HistoryPlugin
from zeep.wsse.utils import WSU

import logging.config

logging.config.dictConfig({
    'version': 1,
    'formatters': {
        'verbose': {
            'format': '%(name)s: %(message)s'
        }
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'verbose',
        },
    },
    'loggers': {
        'zeep.transports': {
            'level': 'DEBUG',
            'propagate': True,
            'handlers': ['console'],
        },
    }
})

# zeep don't follow the docs https://docs.python-zeep.org/en/master/wsse.html
# "To use UsernameToken and Signature together, then you can pass both together to the client in a list" -> *** AttributeError: 'list' object has no attribute 'verify'
class CustomSignature(object):
    """Sign given SOAP envelope with WSSE sig using given key and cert."""
    def __init__(self, wsse_list):
        self.wsse_list = wsse_list
    def apply(self, envelope, headers):
        for wsse in self.wsse_list:
            envelope, headers = wsse.apply(envelope, headers)
        return envelope, headers
    def verify(self, envelope):
        pass

# transport = Transport(cache=SqliteCache())
user_name_token = UsernameToken('xxxx', '')
private_key_filename='mykey.pem'
public_key_filename='mycert.pem'
optional_password='xxxxx'
signature = Signature(private_key_filename, public_key_filename,
    optional_password)


timestamp_token = WSU.Timestamp()
today_datetime = datetime.datetime.today()
expires_datetime = today_datetime + datetime.timedelta(minutes=10)
timestamp_elements = [
        WSU.Created(today_datetime.strftime("%Y-%m-%dT%H:%M:%SZ")),
        WSU.Expires(expires_datetime.strftime("%Y-%m-%dT%H:%M:%SZ"))
]
timestamp_token.extend(timestamp_elements)
# here I don't have a user, do I need it to have a timestamp?
user_name_token = UsernameToken('user', '', timestamp_token=timestamp_token)

client = Client(
    'webServiceBrowsingCards.wsdl',
    wsse=CustomSignature([user_name_token, signature]))
#    wsse=signature,
#    wsse=[user_name_token, signature],

request_type = client.get_type('ns0:getAvailableSources')
bean_type = client.get_type('ns0:accessBean')
beanr = bean_type(systemIP='xxx.xxx.xxx.xxx', systemID='xxxxxxx', systemName='xxxxx')
br_type = client.get_type('ns0:baseRequest')
br = br_type(accessBean=beanr, distinct=0)
request = request_type(arg0=br)
breakpoint()
client.service.getAvailableSources(request)

I get this error:

zeep.transports: HTTP Response from http://sigecweb.beniculturali.it/webServiceBrowsingCards (status: 500):
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><soap:Fault><faultcode xmlns:ns1="http://ws.apache.org/wss4j">ns1:SecurityError</faultcode><faultstring>A security error was encountered when verifying the message</faultstring></soap:Fault></soap:Body></soap:Envelope>
zeep.exceptions.Fault: A security error was encountered when verifying the message

I’ve a java jar wich works and produce a header and body encrypted (capture from LoggingInInterceptor/LoggingOutInterceptor):

  <soap:Header>
    <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" soap:mustUnderstand="1">
      <wsse:BinarySecurityToken EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3" wsu:Id="X509-1D06AFF1B26A357FF616217897768921">binary stuff</wsse:BinarySecurityToken>
      <wsu:Timestamp wsu:Id="TS-1">
        <wsu:Created>2021-05-23T17:09:36.869Z</wsu:Created>
        <wsu:Expires>2021-05-23T17:14:36.869Z</wsu:Expires>
      </wsu:Timestamp>
      <xenc:EncryptedKey xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" Id="EK-1D06AFF1B26A357FF616217897769814">
        <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"/>
        <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
          <wsse:SecurityTokenReference>
            <ds:X509Data>
              <ds:X509IssuerSerial>
                <ds:X509IssuerName>CN=sigec,OU=Unknown,O=ICCD,L=Roma,ST=Roma,C=IT</ds:X509IssuerName>
                <ds:X509SerialNumber>2134296824</ds:X509SerialNumber>
              </ds:X509IssuerSerial>
            </ds:X509Data>
          </wsse:SecurityTokenReference>
        </ds:KeyInfo>
        <xenc:CipherData>
          <xenc:CipherValue>binary stuff</xenc:CipherValue>
        </xenc:CipherData>
        <xenc:ReferenceList>
          <xenc:DataReference URI="#ED-3"/>
          <xenc:DataReference URI="#ED-4"/>
        </xenc:ReferenceList>
      </xenc:EncryptedKey>
      <xenc:EncryptedData xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" Id="ED-4" Type="http://www.w3.org/2001/04/xmlenc#Element">
        <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc"/>
        <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
          <wsse:SecurityTokenReference xmlns:wsse11="http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" wsse11:TokenType="http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKey">
            <wsse:Reference URI="#EK-1D06AFF1B26A357FF616217897769814"/>
          </wsse:SecurityTokenReference>
        </ds:KeyInfo>
        <xenc:CipherData>
          <xenc:CipherValue>binary stuff</xenc:CipherValue>
        </xenc:CipherData>
      </xenc:EncryptedData>
    </wsse:Security>
  </soap:Header>
  <soap:Body xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="Id-103118806">
    <xenc:EncryptedData xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" Id="ED-3" Type="http://www.w3.org/2001/04/xmlenc#Content">
      <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc"/>
      <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
        <wsse:SecurityTokenReference xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsse11="http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd" wsse11:TokenType="http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKey">
          <wsse:Reference URI="#EK-1D06AFF1B26A357FF616217897769814"/>
        </wsse:SecurityTokenReference>
      </ds:KeyInfo>
      <xenc:CipherData>
        <xenc:CipherValue>binary stuff</xenc:CipherValue>
      </xenc:CipherData>
    </xenc:EncryptedData>
  </soap:Body>
</soap:Envelope>

As you can see, everything is encrypted and there’s a timestamp.

As I said before, I don’t understand where Timestamp has to appear.

My code produce this:

<?xml version='1.0' encoding='utf-8'?>
<soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/"><soap-env:Header><wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"><Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<Reference URI="#id-94f34d28-7f58-42f1-93c8-134c53c752c2">
<Transforms>
<Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<DigestValue>TDyLKPG7fCYemJCgHcwi6K4iDA8=</DigestValue>
</Reference>
<Reference URI="#id-a1a1072e-4379-4e63-9332-d8d16087c214">
<Transforms>
<Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<DigestValue>He7d8iTrVAmSlg2d35Siq1PMFzY=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>binary stuff</SignatureValue>
<KeyInfo>
<wsse:SecurityTokenReference><X509Data>
<X509IssuerSerial>
<X509IssuerName>issuers info</X509IssuerName>
<X509SerialNumber>929749877</X509SerialNumber>
</X509IssuerSerial>
<X509Certificate>binary stuff</X509Certificate>
</X509Data>
</wsse:SecurityTokenReference></KeyInfo>
</Signature>
<wsse:UsernameToken>
<wsse:Username>user</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText"></wsse:Password></wsse:UsernameToken>
<wsu:Timestamp xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="id-a1a1072e-4379-4e63-9332-d8d16087c214">
<wsu:Created>2021-05-23T19:34:54Z</wsu:Created>
<wsu:Expires>2021-05-23T19:44:54Z</wsu:Expires>
</wsu:Timestamp></wsse:Security>
</soap-env:Header>
<soap-env:Body xmlns:ns1="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" ns1:Id="id-94f34d28-7f58-42f1-93c8-134c53c752c2">
<ns0:getAvailableSources xmlns:ns0="http://webservice.sigec.iccd.it/"><arg0 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ns0:getAvailableSources">
<arg0>
<accessBean>
<systemID>xxx</systemID>
<systemIP>xxx.xxx.xxx.xxx</systemIP>
<systemName>xxxxx</systemName>
</accessBean>
<distinct>false</distinct>
</arg0>
</arg0>
</ns0:getAvailableSources>
</soap-env:Body>
</soap-env:Envelope>

Any idea/example/hint? Certs are ok.

Thanks very much for any info!

#xml #web-services #encryption #soap #digital-signature

Вопрос:

Я пытаюсь запросить веб-службы, которые реализованы на основе стандартов OASIS. стек веб-служб поддерживает WS-Security и WS-SecurityPolicy для настройки обработки безопасности

Я использовал эту библиотеку php для подписи и шифрования своего запроса, https://github.com/robrichards/wse-php/blob/master/examples/soap-sign-encrypt.php

Мое требование таково

  1. цифровая подпись Имя пользователя,метка времени и тело с использованием закрытого ключа и подписи включают элемент информации о ключе, содержащий сведения о сертификате X. 509
  2. после подписания зашифруйте имя пользователя и тело с помощью открытого ключа

Я попытался выполнить образец запроса без подписи и шифрования

 <?xml version="1.0"?>
<soapenv:Envelope
    xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:dit=""
    xmlns:req="">
    <soapenv:Header>
        <wsse:Security
            xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" soapenv:mustUnderstand="1">
            <wsse:UsernameToken>
                <wsse:Username>XXXXX</wsse:Username>
                <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">XXXX</wsse:Password>
                <wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">uB GW2PHDDR3t dTz7bNJguBQgLqlR5 R0=</wsse:Nonce>
                <wsu:Created
                    xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">2021-05-17T08:46:53Z
                </wsu:Created>
            </wsse:UsernameToken>
            <wsu:Timestamp
                xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
                <wsu:Created>2021-05-17T08:46:53Z</wsu:Created>
                <wsu:Expires>2021-05-17T08:52:53Z</wsu:Expires>
            </wsu:Timestamp>
        </wsse:Security>
    </soapenv:Header>
    <soapenv:Body>
        <dit:getAddClientServicecDetails>
            <dit:DitRequest uniqueRequestId="XXXXXXXX">
                <req:pan>CFXXXXXXXXXX</req:pan>
                <req:dob>XX/XX/XXXX</req:dob>
            </dit:DitRequest>
        </dit:getAddClientServicecDetails>
    </soapenv:Body>
</soapenv:Envelope>
 

Получите следующий ответ, помогите мне в устранении следующей проблемы

 <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><soap:Fault><faultcode>soap:Server</faultcode><faultstring>These policy alternatives can not be satisfied: 
{http://schemas.xmlsoap.org/ws/2005/07/securitypolicy}AsymmetricBinding: Received Timestamp does not match the requirements
{http://schemas.xmlsoap.org/ws/2005/07/securitypolicy}InitiatorToken
{http://schemas.xmlsoap.org/ws/2005/07/securitypolicy}X509Token: The received token does not match the token inclusion requirement
{http://schemas.xmlsoap.org/ws/2005/07/securitypolicy}RecipientToken
{http://schemas.xmlsoap.org/ws/2005/07/securitypolicy}IncludeTimestamp
{http://schemas.xmlsoap.org/ws/2005/07/securitypolicy}OnlySignEntireHeadersAndBody
{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}SignedEncryptedSupportingTokens: The received token does not match the signed encrypted supporting token requirement
{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}SignedParts: {http://schemas.xmlsoap.org/soap/envelope/}Body not SIGNED
{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}EncryptedParts: {http://schemas.xmlsoap.org/soap/envelope/}Body not ENCRYPTED</faultstring></soap:Fault></soap:Body></soap:Envelope>
 

После добавления подписи и шифрования возникает следующая ошибка

 <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><soap:Fault><faultcode xmlns:ns1="http://ws.apache.org/wss4j">ns1:SecurityError</faultcode><faultstring>A security error was encountered when verifying the message</faultstring></soap:Fault></soap:Body></soap:Envelope>
 

Будет полезно, если вы поделитесь некоторыми допустимыми образцами xml для справки. Спасибо

Со вчерашнего дня я пытаюсь интегрировать безопасность в свое мыло веб-сервисов (с apache cxf) через ws-security. Для этого у меня есть следующая конфигурация: —my endppoint и конфигурация его перехватчиков:

@Configuration 
@ImportResource({"classpath:META-INF/cxf/cxf.xml"})
@ComponentScan(basePackages ={"com.nhit.dev"})
public class MyConfig extends SpringBootServletInitializer{



@Bean
public IServicesWeb momoService() {
    return new MomoServices();
}

@Bean(name = Bus.DEFAULT_BUS_ID)
public SpringBus springBus() {
    return new SpringBus();
} 


@Bean
public ServletRegistrationBean cxfServlet() {
    ServletRegistrationBean servlet = new ServletRegistrationBean(new   CXFServlet(), "/services/*");
    servlet.setLoadOnStartup(1);
    return servlet;
}

@Bean
public Endpoint endpoint() {

EndpointImpl endpoint = new EndpointImpl(springBus(), momoService());
endpoint.publish("/momo");
Map<String, Object> inProps = new HashMap<String, Object>();
inProps.put("action", "UsernameToken");
inProps.put("passwordType", "PasswordText");
inProps.put("passwordCallbackClass",  "com.nhit.dev.mobilepayment.web.WsPwdCallBack");
endpoint.getInInterceptors().add(new WSS4JInInterceptor(inProps));

        Map<String, Object> outProps = new HashMap<String, Object>();
    outProps.put("action", "UsernameToken");
    outProps.put("user", "abc");
    outProps.put("passwordType", "PasswordText");
    outProps.put("passwordCallbackClass", "com.nhit.dev.mobilepayment.web.WsPwdCallBack");
    endpoint.getOutInterceptors().add(new WSS4JOutInterceptor(outProps));
    return endpoint;
}

}

— мой обработчик класса PasswordCallBack:

public class WsPwdCallBack implements CallbackHandler{

protected final Log logger = LogFactory.getLog(getClass());

private Map<String, String> passwords = new HashMap<String, String>();

public WsPwdCallBack() {
    passwords.put("abc", "abc");
    passwords.put("xyz", "xyz");
}

public void handle(Callback[] callbacks) throws IOException,
        UnsupportedCallbackException {
    for (int i = 0; i < callbacks.length; i++) {
        WSPasswordCallback pc = (WSPasswordCallback) callbacks[i];

        String pass = passwords.get(pc.getIdentifier());
        if (pass != null) {
            pc.setPassword(pass);
            return;
        }
    }
}

}

— наконец мой запрос на мыло от soapUI:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://webservices.web.mobilepayment.dev.nhit.com/" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
   <soapenv:Header>
    <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" soapenv:mustUnderstand="1">
         <wsse:UsernameToken wsu:Id="UsernameToken-87b7b0c5-31fe-4a01-b333-f9ca564ded57">
            <wsse:Username>xyz</wsse:Username>
            <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">TlPGdyb/NOoeA2KMO0n6DbmA0AA=</wsse:Password>
            <wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">FCG+tTtuZXguO8nUQUQeIQ==</wsse:Nonce>
            <wsu:Created>2016-12-08T12:12:00.Z</wsu:Created>
         </wsse:UsernameToken>
      </wsse:Security>
   </soapenv:Header>
   <soapenv:Body>
      <web:creerDevise>
         <!--Optional:-->
         <libelle>Livre</libelle>
      </web:creerDevise>
   </soapenv:Body>
</soapenv:Envelope>

Из SOAPUI, когда я выполняю этот запрос, я получаю следующую ошибку:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
      <soap:Fault>
         <faultcode xmlns:ns1="http://ws.apache.org/wss4j">ns1:SecurityError</faultcode>
         <faultstring>A security error was encountered when verifying the message</faultstring>
      </soap:Fault>
   </soap:Body>
</soap:Envelope>

Итак, я собираюсь взглянуть на журналы wildfly, в которых я развернул архив .ear моего приложения; И вот я увидел это исключение:

Вызвано: org.apache.wss4j.common.ext.WSSecurityException: срок действия сообщения истек

Пожалуйста, помогите мне это исправить, я новичок в ws-security. Я не знаю, как разрешить это исключение.

1 ответ

Лучший ответ

WSS4J применяет ограничение по времени в 5 минут по умолчанию для метки времени создания UsernameToken. Таким образом, в пользовательском интерфейсе SOAP вам необходимо воссоздать фрагмент UsernameToken, если с момента его последнего создания прошло более 5 минут. В качестве альтернативы вы можете настроить WSS4J, чтобы разрешить более длительный срок действия.


1

Colm O hEigeartaigh
8 Дек 2016 в 13:22

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Fault или error
  • Fault mistake error wrong blame defect разница
  • Fault in drive bmw e60 ошибка
  • Fault can кариер вектор 1350 перевод ошибка
  • Fault 202 ошибка рено магнум

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии