Soap

Servicios Web con Perl

  • admin 

El lenguaje Perl cuenta principalmente con dos módulos que pueden ser usados para crear servicios web de manera fácil y rápida, desde cero o reutilizando aplicaciones de Perl ya existentes.Éstos módulos son SOAP::Lite y WSDL::Generator. A continuación se explicarán cada uno de ellos y se mostrará un ejemplo de su uso.

Tabla de contenidos

SOAP::Lite

SOAP::Lite es un conjunto de módulos de Perl que proveen una interfaz simple y liviana para el protocolo SOAP, tanto en el lado cliente como en el del servidor. SOAP::Lite es actualmente el kit de desarrollo de web services para Perl más difundido y utilizado. Su página en SourceForge ha registrado más de 10,700 descargas en casi 2 años.

SOAP::Lite provee clases para implementar funcionalidades de un cliente SOAP, varios servidores, soporte a datos y muchas otras tareas. La siguiente es una lista resumida de sus características:

Soporte de Protocolos

  • Soporta las especificaciones SOAP 1.1 y SOAP 1.2.
  • Incluye XMLRPC::Lite, una implementación del protocolo XML-RPC en el lado del cliente y del servidor. Entre los protocolos de trasporte disponibles, están HTTP, SMTP, POP3 y TCP.
  • Soporta publicación y peticiones UDDI del lado del cliente, a través de un API.

Interoperabilidad

  • Se han realizado pruebas de interoperabilidad con diferentes implementaciones: Apache SOAP, Frontier, Microsoft SOAP, Microsoft .NET, DevelopMentor, XMethods, 4s4c, Phalanx, Kafka, SQLData, Lucin (en Java, Perl, C++, Python, VB, COM, XSLT).

Protocolos de Transporte

  • Provee implementaciones de servidores TCP con multiservidor “no-bloqueante”
  • Soporta transporte sobre Jabber, MQSeries y SMTP.
  • Provee compresión transparente para HTTP.
  • Soporta el protocolo HTTPS.
  • Provee soporte para proxy.
  • Provee implementaciones de servidor POP3.
  • Soporta M-POST y redirección HTTP.

Soporte para WSDL

  • Soporta el esquema WSDL con “stub” y acceso en tiempo de ejecución. Soporta descripciones de servicio por directivas y cortas (tModel).

Otras

  • Provee implementaciones de servidores CGI, daemon, mod_perl, Apache::Registry yFastCGI.
  • Incluye los módulos de Apache mod_soap y mod_xmlrpc, los cuales permiten crear servidores SOAP o XML-RPC con algunas líneas en los archivos .htaccess o httpd.conf.
  • Soporta el enlace dinámico y estático de clases y métodos.
  • Provee un intérprete de comandos para sesiones SOAP interactivas.
  • Incluye una gran cantidad de ejemplos.

WSDL::Generator

WSDL::Generator es un módulo de Perl para crear archivos de descripción de servicios (WSDL) automáticamente a partir de módulos de perl expuestos como servicios web. Éste módulo, desarrollado por Pierre Denis <pdenis@fotango.com>, es tal vez el único que se ha creado hasta ahora con ésta funcionalidad en el mundo de Perl. SOAP::Lite y WSDL::Generator en la Práctica

Ejemplo

A continuación, se muestra un ejemplo de la utilización del lenguaje Perl para exponer un servicio web sencillo. En la documentación de los módulos puede encontrarse una descripción extendida de todas las funcionalidades que poseen y cómo utilizarlas.

El siguiente es el código fuente de un módulo de Perl que implementa una clase llamada “Cafetera”, con un único método llamado “prepararCafe”, que recibe como parámetro el número de tasas y devuelve como resultado un mensaje indicando el número de tasas preparadas:

Código del archivo Cafetera.pm <perl>

#!/usr/bin/perl -w
# Servicio web de ejemplo
package Cafetera;
use strict;
# Este es el constructor
sub new{
 my $proto = shift;
 my $class = ref($proto) || $proto;
 my $tasas = 0;
 bless($tasas,$class);
}
sub prepararCafe{
 shift;
 my $tasas = shift;
 print STDERR "Llamado con el parámetro $tasas";
 return "Se prepararon ".$tasas." tasas";
}
1;

</perl> A continuación se muestra el uso del módulo SOAP::Lite para exponer el módulo Cafetera como un servicio web, usando el servidor tipo SOAP::Transport::HTTP::Daemon:

Código del archivo servidor.pl <perl>

#!/usr/bin/perl -w
# Servidor SOAP
use SOAP::Transport::HTTP;
use Cafetera;
#En el parámetro dispatch_to se especifica la ruta a los módulos disponibles
my $daemonio = SOAP::Transport::HTTP::Daemon
 -> new(LocalAddr => 'localhost', LocalPort => 8070)
 -> dispatch_to('/home/tesis/thewala/preparacion/P.5-IP/productos/servicio-en-perl','Cafetera')
;
print "La url del daemonio es:".$daemonio->url()." ";
$daemonio->handle();

</perl> Desde éste momento, cualquier aplicación puede empezar a consumir el servicio web, si sabe cómo invocarlo. A continuación se muestra un cliente del servicio hecho en Perl con SOAP::Lite:

Código del archivo cliente.pl <perl>

#!/usr/bin/perl -w
use strict;
use SOAP::Lite;
my $soap = SOAP::Lite
 ->uri('http://localhost:8070/Cafetera')
 ->proxy('http://localhost:8070/')
;
my $resultado= $soap->prepararCafe(5)->result;
print "Preparando cafe: ".$resultado." ";

</perl> Para que aplicaciones hechas en otros lenguajes o que no saben cómo invocar el servicio puedan acceder al mismo, se debe crear el archivo de descripción WSDL. A continuación se muestra el guión o “script” de perl que utiliza WSDL::Generator para crear el archivo WSDL:

Código del archivo generar-wsdl.pl <perl>

#!/usr/bin/perl -w
use WSDL::Generator;
my $init = {
 'schema_namesp' => 'http://localhost:8070/Cafetera.xsd',
 'services' => 'Cafetera',
 'service_name' => 'Cafetera',
 'target_namesp' => 'http://localhost:8070/Cafetera.wsdl',
 'documentation' => 'Servicio Web de Prueba',
 'location' => 'http://localhost:8070/Cafetera'
};
my $w = WSDL::Generator->new($init);
Cafetera->prepararCafe(5);
print $w->get(Cafetera);

</perl> La salida de este guión de Perl constituye el documento wsdl que debe ser publicado para que cualquiera pueda acceder al servicio Cafetera. La siguiente es la salida del guión, la cuál puede guardarse en el archivo Cafetera.wsdl:

Código del archivo Cafetera.wsdl <xml>

<?xml version="1.0"?>
<definitions
 name="Cafetera"
 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
 xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
 targetNamespace="http://localhost:8070/Cafetera.wsdl"
 xmlns:tns="http://localhost:8070/Cafetera.wsdl"
 xmlns="http://schemas.xmlsoap.org/wsdl/"
 xmlns:xsdl="http://localhost:8070/Cafetera.xsd">
<types>
 <xsd:schema targetNamespace="http://localhost:8070/Cafetera.xsd">
  <xsd:element name="prepararCafeRequest" type="xsd:string" />
  <xsd:element name="prepararCafeResponse" type="xsd:string" />
 </xsd:schema>
</types>
<message name="prepararCafeRequest">
 <part name="prepararCafeRequestSoapMsg" element="xsdl:prepararCafeRequest"/>
</message>
<message name="prepararCafeResponse">
 <part name="prepararCafeResponseSoapMsg" element="xsdl:prepararCafeResponse"/>
</message>
<portType name="CafeteraCafeteraPortType">
 <operation name="prepararCafe">
  <input message="tns:prepararCafeRequest" />
  <output message="tns:prepararCafeResponse" />
 </operation>
</portType>
<binding name="CafeteraCafeteraBinding" type="tns:CafeteraCafeteraPortType">
 <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
 <operation name="prepararCafe">
  <soap:operation style="document" soapAction=""/>
  <input>
   <soap:body use="literal"/>
  </input>
  <output>
   <soap:body use="literal"/>
  </output>
 </operation>
</binding>
<service name="Cafetera">
<documentation>
 Servicio Web de Prueba
</documentation>
<port name="CafeteraCafeteraPort" binding="tns:CafeteraCafeteraBinding">
 <soap:address location="http://localhost:8070/Cafetera"/>
</port>
</service>
</definitions>

</xml>

Referencias

 

WS-Security

  • admin 

Tipicamente siempre hemos trabajado con Soap con la seguridad garantizada mediante encriptación en el tunel o mediante https. Recientemente nos encontramos con que la seguridad se garantiza mediante el uso de los mecanismos mencionados, además del uso de certificados.

Adjuntaré artículos explicativos sobre esta nueva situación.

http://en.wikipedia.org/wiki/WS-Security

WS-Security

From Wikipedia, the free encyclopedia

WS-Security (Web Services Security, short WSS) is a flexible and feature-rich extension to SOAP to apply security to web services. It is a member of the WS-* family of web service specificationsand was published by OASIS.

The protocol specifies how integrity and confidentiality can be enforced on messages and allows the communication of various security token formats, such as SAML, Kerberos, and X.509. Its main focus is the use of XML Signature and XML Encryption to provide end-to-end security.

Contents

  • 1 Features
  • 2 Use Cases
    • 2.1 Transport Layer Security (Without WS-Security)
    • 2.2 End-to-end security
    • 2.3 Non-Repudiation
    • 2.4 Alternative transport bindings
    • 2.5 Reverse proxy/common security token
  • 3 Issues
  • 4 Performance
  • 5 History
  • 6 Associated specifications
  • 7 See also
  • 8 Alternative
  • 9 External links
  • 10 References

Features

WS-Security describes three main mechanisms:

  • How to sign SOAP messages to assure integrity. Signed messages provide also non-repudiation.
  • How to encrypt SOAP messages to assure confidentiality.
  • How to attach security tokens to ascertain the sender’s identity .

The specification allows a variety of signature formats, encryptions algorithms and multiple trust domains, and is open to various security token models, such as:

  • X.509 certificates
  • Kerberos tickets
  • UserID/Password credentials
  • SAML-Assertion
  • Custom defined token

The token formats and semantics are defined in the associated profile documents.

WS-Security incorporates security features in the header of a SOAP message, working in the application layer.

These mechanisms by themselves do not provide a complete security solution for Web services. Instead, this specification is a building block that can be used in conjunction with other Web service extensions and higher-level application-specific protocols to accommodate a wide variety of security models and security technologies. In general, WSS by itself does not provide any guarantee of security. When implementing and using the framework and syntax, it is up to the implementor to ensure that the result is not vulnerable.

Key management, trust bootstrapping, federation and agreement on the technical details (ciphers, formats, algorithms) is outside the scope of WS-Security.

Use Cases

Transport Layer Security (Without WS-Security)

The typical SOAP use case with a communication between trusted peers (using HTTPS) does not need WS-Security at all. It is described in Alternative, and reduces complexity and improves performance.

End-to-end security

If a SOAP intermediary is required, and the intermediary is not or less trusted, messages need to be signed and optionally encrypted. This might be the case of an application level proxy at a network perimeter, that will terminate TCP connections.

Non-Repudiation

The standard method for non-repudiation is to write transactions to an audit trail, that is subject to specific security safeguards. However, if the audit trail is not sufficient, digital signatures may provide a better method to enforce non-repudiation. WS-Security can provide this.

Alternative transport bindings

Although almost all SOAP services implement HTTP bindings, in theory other bindings such as JMS or SMTP could be used; in this case end-to-end security would be required.

Reverse proxy/common security token

Even if the web service relies upon transport layer security, it might be required for the service to know about the end user, if the service is relayed by a (HTTP-) reverse proxy. A WSS-header could be used to convey the end user’s token, vouched for by the reverse proxy.

Issues

  • If there are frequent message exchanges between service provider and consumer, the overhead of XML SIG and XML ENC are significant. If end-to-end security is required, a protocol like WS-SecureConversation may reduce the overhead. If sufficient, use only encryption or signing, as the combination of both is significantly slower than the mere sum of the single operations. SeePerformance below.
  • The merging of several XML-schemata like SOAP, SAML, XML ENC, XML SIG might cause dependencies on different versions of library functions like canonicalization and parsing, that are difficult to manage in an application server.

Performance

WS-Security adds significant overhead to SOAP-processing due to the increased size of the message on the wire, XML and cryptographic processing, requiring faster CPUs and more memory and bandwidth.

An evaluation in 2005 [1] measured 25 types of SOAP messages of different size and complexity processed by WSS4J with both WS-Security and WS-SecureConversation on a Pentium 4/2,8 GHz CPU. Some findings were:

  • Encryption was faster than signing
  • Encryption and signing together were 2-7 times slower than signing alone and produced significantly bigger documents.
  • Depending on the type of message, WS-SecureConversation either made no difference or reduced processing time by half in the best case.
  • It took less than 10 milliseconds to sign or encrypt up to an array of 100 kilo bytes, but it took about 100~200 to perform the security operations for SOAP.

Another benchmark in 2006[2] resulted in this comparison:

Security Mechanism Messages/second
WS-Security (X.509) XML Signature & Encryption 352
WS-SecureConversation XML Signature & Encryption 798
Transport Layer Security 2918

History

Web services initially relied on the underlying transport security. In fact, most implementations still do[citation needed]. As SOAP allows for multiple transport bindings, such as HTTP and SMTP, an SOAP-level security mechanism was needed. The lack of end-to-end security because of the dependence on transport security was another factor.

The protocol was originally developed by IBM, Microsoft, and VeriSign. Their original specification[3][4] was published on April 5, 2002, and was followed up by an addendum[5] on August 18, 2002.

In 2002, 2 proposals were submitted to the OASIS WSS Technical Committee[6]: Web Service Security (WS-Security) and Web Services Security Addendum. As a result, WS-Security was published:

  • WS-Security 1.0 was released on April 19, 2004
  • Version 1.1 was released on February 17, 2006

The version 1.0 standard published by OASIS contained a number of significant differences to the standard proposed by the IBM, Microsoft and VeriSign consortium. Many systems were developed using the proposed standard and the differences made them incompatible with systems developed to the OASIS standard.

Some refer to the pre-OASIS specification as the «WS-Security Draft 13»[7], or as the Web Services Security Core Specification. However these names are not widely known and indeed today it is hard to clearly identify whether an application or server is using a pre- or post-OASIS specification. Most forum posts use the keyword «WSSE» to refer to the pre-OASIS version because it mandated the use of a «wsse» XML namespace prefix to the http://schemas.xmlsoap.org/ws/2002/07/secext url (and similar urls of different versions).

The protocol is currently officially called WSS and developed via committee in Oasis-Open.

Associated specifications

The following draft specifications are associated with WS-Security:

  • WS-Federation
  • WS-Privacy
  • WS-Test

The following approved specifications are associated with WS-Security:

  • WS-Policy
  • WS-Trust
  • WS-SecureConversation

See also

  • .NET Web Services Enhancements
  • List of Web service specifications (WS-*)
  • SAML
  • WS-I Basic Security Profile
  • Web service
  • X.509
  • XACML
  • XML Encryption
  • XML firewall

Alternative

In point-to-point situations confidentiality and data integrity can also be enforced on Web services through the use of Transport Layer Security (TLS), for example, by sending messages over https. WS-Security however addresses the wider problem of maintaining integrity and confidentiality of messages until after a message was sent from the originating node, providing so called end to end security.

Applying TLS can significantly reduce the overhead involved by removing the need to encode keys and message signatures into XML before sending. A challenge in using TLS would be if messages needed to go through an application level proxy server, as it would need to be able to see the request for routing. In such an example, the server would see the request coming from the proxy, not the client; this could be worked around by having the proxy have a copy of the client’s key and certificate, or by having a signing certificate trusted by the server, with which it could generate a key/certificate pair matching those of the client. However, as the proxy is operating on the message, it does not ensure end-to-end security, but only ensures point-to-point security.

External links

  • OASIS Web Services Security TC (Contains links to download specification documents)
  • WS-Security Specification (IBM)
  • WS-I Basic Security Profile
  • Web Services Security Documentation
  • Web Service Security Patterns (Microsoft)
  • WSS4J (WS-Security Java Implementation from Apache)
  • Apache Rampart (WS-Security Java Implementation from Apache Axis2)
  • WSIT Web Services Interoperability Technologies (WSIT) that enable interoperability between the Java platform and Windows Communication Foundation (WCF)
  • python ws-security example

References

  1. ^ Hongbin Liu, Shrideep Pallickara, Geoffrey Fox: Performance of Web Services Security
  2. ^ Francois Lascelles, Aaron Flint: WS Security Performance. Secure Conversation versus the X509 Profile
  3. ^ Bob Atkinson, et. al.: Web Services Security (WS-Security)
  4. ^ Bob Atkinson, et. al.: Web Services Security (WS-Security)
  5. ^ Giovanni Della-Libera, Phillip Hallam-Baker Maryann Hondo: Web Services Security Addendum
  6. ^ OASIS Web Services Security TC
  7. ^ Web Services Security: SOAP Message Security – Working Draft 13