NetSSL library refactoring

This commit is contained in:
Guenter Obiltschnig
2009-02-23 20:56:01 +00:00
parent f345a6c6e2
commit 75a07d7983
103 changed files with 9549 additions and 1453 deletions

View File

@@ -1,7 +1,7 @@
// //
// DateTimeParser.cpp // DateTimeParser.cpp
// //
// $Id: //poco/svn/Foundation/src/DateTimeParser.cpp#3 $ // $Id: //poco/Main/Foundation/src/DateTimeParser.cpp#18 $
// //
// Library: Foundation // Library: Foundation
// Package: DateTime // Package: DateTime
@@ -103,14 +103,11 @@ void DateTimeParser::parse(const std::string& fmt, const std::string& str, DateT
break; break;
case 'y': case 'y':
SKIP_JUNK(); SKIP_JUNK();
PARSE_NUMBER(year); PARSE_NUMBER_N(year, 2);
if (year < 1000) if (year >= 70)
{ year += 1900;
if (year >= 70) else
year += 1900; year += 2000;
else
year += 2000;
}
break; break;
case 'Y': case 'Y':
SKIP_JUNK(); SKIP_JUNK();

View File

@@ -1,7 +1,7 @@
// //
// DatagramSocket.h // DatagramSocket.h
// //
// $Id: //poco/svn/Net/include/Poco/Net/DatagramSocket.h#2 $ // $Id: //poco/Main/Net/include/Poco/Net/DatagramSocket.h#3 $
// //
// Library: Net // Library: Net
// Package: Sockets // Package: Sockets
@@ -56,7 +56,7 @@ public:
DatagramSocket(); DatagramSocket();
/// Creates an unconnected IPv4 datagram socket. /// Creates an unconnected IPv4 datagram socket.
DatagramSocket(IPAddress::Family family); explicit DatagramSocket(IPAddress::Family family);
/// Creates an unconnected datagram socket. /// Creates an unconnected datagram socket.
/// ///
/// The socket will be created for the /// The socket will be created for the

View File

@@ -1,7 +1,7 @@
// //
// DialogSocket.h // DialogSocket.h
// //
// $Id: //poco/svn/Net/include/Poco/Net/DialogSocket.h#2 $ // $Id: //poco/Main/Net/include/Poco/Net/DialogSocket.h#3 $
// //
// Library: Net // Library: Net
// Package: Sockets // Package: Sockets
@@ -70,7 +70,7 @@ public:
/// Before sending or receiving data, the socket /// Before sending or receiving data, the socket
/// must be connected with a call to connect(). /// must be connected with a call to connect().
DialogSocket(const SocketAddress& address); explicit DialogSocket(const SocketAddress& address);
/// Creates a stream socket and connects it to /// Creates a stream socket and connects it to
/// the socket specified by address. /// the socket specified by address.

View File

@@ -1,7 +1,7 @@
// //
// HTTPClientSession.h // HTTPClientSession.h
// //
// $Id: //poco/svn/Net/include/Poco/Net/HTTPClientSession.h#2 $ // $Id: //poco/Main/Net/include/Poco/Net/HTTPClientSession.h#7 $
// //
// Library: Net // Library: Net
// Package: HTTPClient // Package: HTTPClient
@@ -169,8 +169,9 @@ protected:
int write(const char* buffer, std::streamsize length); int write(const char* buffer, std::streamsize length);
/// Tries to re-connect if keep-alive is on. /// Tries to re-connect if keep-alive is on.
virtual std::string getHostInfo() const; virtual std::string proxyRequestPrefix() const;
/// Returns the target host and port number for proxy requests. /// Returns the prefix prepended to the URI for proxy requests
/// (e.g., "http://myhost.com").
void deleteResponseStream(); void deleteResponseStream();
/// Deletes the response stream and sets it to 0. /// Deletes the response stream and sets it to 0.

View File

@@ -1,7 +1,7 @@
// //
// HTTPSession.h // HTTPSession.h
// //
// $Id: //poco/Main/Net/include/Poco/Net/HTTPSession.h#5 $ // $Id: //poco/Main/Net/include/Poco/Net/HTTPSession.h#7 $
// //
// Library: Net // Library: Net
// Package: HTTP // Package: HTTP
@@ -96,7 +96,13 @@ public:
{ {
HTTP_PORT = 80 HTTP_PORT = 80
}; };
StreamSocket detachSocket();
/// Detaches the socket from the session.
///
/// The socket is returned, and a new, uninitialized socket is
/// attached to the session.
protected: protected:
HTTPSession(); HTTPSession();
/// Creates a HTTP session using an /// Creates a HTTP session using an
@@ -154,12 +160,16 @@ protected:
/// Connects the underlying socket to the given address /// Connects the underlying socket to the given address
/// and sets the socket's receive timeout. /// and sets the socket's receive timeout.
void attachSocket(const StreamSocket& socket);
/// Attaches a socket to the session, replacing the
/// previously attached socket.
void close(); void close();
/// Closes the underlying socket. /// Closes the underlying socket.
void setException(const Poco::Exception& exc); void setException(const Poco::Exception& exc);
/// Stores a clone of the exception. /// Stores a clone of the exception.
private: private:
enum enum
{ {

View File

@@ -1,7 +1,7 @@
// //
// HTTPStreamFactory.h // HTTPStreamFactory.h
// //
// $Id: //poco/svn/Net/include/Poco/Net/HTTPStreamFactory.h#2 $ // $Id: //poco/Main/Net/include/Poco/Net/HTTPStreamFactory.h#3 $
// //
// Library: Net // Library: Net
// Package: HTTP // Package: HTTP
@@ -83,6 +83,10 @@ public:
static void registerFactory(); static void registerFactory();
/// Registers the HTTPStreamFactory with the /// Registers the HTTPStreamFactory with the
/// default URIStreamOpener instance. /// default URIStreamOpener instance.
static void unregisterFactory();
/// Unregisters the HTTPStreamFactory with the
/// default URIStreamOpener instance.
private: private:
enum enum

View File

@@ -1,7 +1,7 @@
// //
// MulticastSocket.h // MulticastSocket.h
// //
// $Id: //poco/svn/Net/include/Poco/Net/MulticastSocket.h#2 $ // $Id: //poco/Main/Net/include/Poco/Net/MulticastSocket.h#3 $
// //
// Library: Net // Library: Net
// Package: Sockets // Package: Sockets
@@ -58,7 +58,7 @@ public:
MulticastSocket(); MulticastSocket();
/// Creates the MulticastSocket. /// Creates the MulticastSocket.
MulticastSocket(IPAddress::Family family); explicit MulticastSocket(IPAddress::Family family);
/// Creates an unconnected datagram socket. /// Creates an unconnected datagram socket.
/// ///
/// The socket will be created for the /// The socket will be created for the

View File

@@ -1,7 +1,7 @@
// //
// POP3ClientSession.h // POP3ClientSession.h
// //
// $Id: //poco/svn/Net/include/Poco/Net/POP3ClientSession.h#2 $ // $Id: //poco/Main/Net/include/Poco/Net/POP3ClientSession.h#3 $
// //
// Library: Net // Library: Net
// Package: Mail // Package: Mail
@@ -76,7 +76,7 @@ public:
typedef std::vector<MessageInfo> MessageInfoVec; typedef std::vector<MessageInfo> MessageInfoVec;
POP3ClientSession(const StreamSocket& socket); explicit POP3ClientSession(const StreamSocket& socket);
/// Creates the POP3ClientSession using /// Creates the POP3ClientSession using
/// the given socket, which must be connected /// the given socket, which must be connected
/// to a POP3 server. /// to a POP3 server.

View File

@@ -1,7 +1,7 @@
// //
// SMTPClientSession.h // SMTPClientSession.h
// //
// $Id: //poco/Main/Net/include/Poco/Net/SMTPClientSession.h#4 $ // $Id: //poco/Main/Net/include/Poco/Net/SMTPClientSession.h#5 $
// //
// Library: Net // Library: Net
// Package: Mail // Package: Mail
@@ -67,10 +67,10 @@ public:
{ {
AUTH_NONE, AUTH_NONE,
AUTH_CRAM_MD5, AUTH_CRAM_MD5,
AUTH_LOGIN AUTH_LOGIN,
}; };
SMTPClientSession(const StreamSocket& socket); explicit SMTPClientSession(const StreamSocket& socket);
/// Creates the SMTPClientSession using /// Creates the SMTPClientSession using
/// the given socket, which must be connected /// the given socket, which must be connected
/// to a SMTP server. /// to a SMTP server.

View File

@@ -1,7 +1,7 @@
// //
// SocketAcceptor.h // SocketAcceptor.h
// //
// $Id: //poco/svn/Net/include/Poco/Net/SocketAcceptor.h#2 $ // $Id: //poco/Main/Net/include/Poco/Net/SocketAcceptor.h#3 $
// //
// Library: Net // Library: Net
// Package: Reactor // Package: Reactor
@@ -89,7 +89,7 @@ class SocketAcceptor
/// if special steps are necessary to create a ServiceHandler object. /// if special steps are necessary to create a ServiceHandler object.
{ {
public: public:
SocketAcceptor(ServerSocket& socket): explicit SocketAcceptor(ServerSocket& socket):
_socket(socket), _socket(socket),
_pReactor(0) _pReactor(0)
/// Creates an SocketAcceptor, using the given ServerSocket. /// Creates an SocketAcceptor, using the given ServerSocket.

View File

@@ -1,7 +1,7 @@
// //
// SocketConnector.h // SocketConnector.h
// //
// $Id: //poco/svn/Net/include/Poco/Net/SocketConnector.h#2 $ // $Id: //poco/Main/Net/include/Poco/Net/SocketConnector.h#3 $
// //
// Library: Net // Library: Net
// Package: Reactor // Package: Reactor
@@ -93,7 +93,7 @@ class SocketConnector
/// if special steps are necessary to create a ServiceHandler object. /// if special steps are necessary to create a ServiceHandler object.
{ {
public: public:
SocketConnector(SocketAddress& address): explicit SocketConnector(SocketAddress& address):
_pReactor(0) _pReactor(0)
/// Creates a SocketConnector, using the given Socket. /// Creates a SocketConnector, using the given Socket.
{ {

View File

@@ -1,7 +1,7 @@
// //
// SocketImpl.h // SocketImpl.h
// //
// $Id: //poco/svn/Net/include/Poco/Net/SocketImpl.h#3 $ // $Id: //poco/Main/Net/include/Poco/Net/SocketImpl.h#6 $
// //
// Library: Net // Library: Net
// Package: Sockets // Package: Sockets
@@ -335,7 +335,7 @@ public:
int socketError(); int socketError();
/// Returns the value of the SO_ERROR socket option. /// Returns the value of the SO_ERROR socket option.
poco_socket_t sockfd(); poco_socket_t sockfd() const;
/// Returns the socket descriptor for the /// Returns the socket descriptor for the
/// underlying native socket. /// underlying native socket.
@@ -383,13 +383,9 @@ protected:
/// The third argument, proto, is normally set to 0, /// The third argument, proto, is normally set to 0,
/// except for raw sockets. /// except for raw sockets.
void setSockfd(poco_socket_t aSocket); void reset(poco_socket_t fd = POCO_INVALID_SOCKET);
/// Allows subclasses to set the socket manually, iff no valid socket is set yet! /// Allows subclasses to set the socket manually, iff no valid socket is set yet!
void invalidate();
/// Sets a socket to POCO_INVALID_SOCKET. It is assumed that the socket was closed
/// via a prior operation.
static int lastError(); static int lastError();
/// Returns the last error code. /// Returns the last error code.
@@ -424,7 +420,7 @@ private:
// //
// inlines // inlines
// //
inline poco_socket_t SocketImpl::sockfd() inline poco_socket_t SocketImpl::sockfd() const
{ {
return _sockfd; return _sockfd;
} }
@@ -446,12 +442,6 @@ inline int SocketImpl::lastError()
} }
inline void SocketImpl::invalidate()
{
_sockfd = POCO_INVALID_SOCKET;
}
inline bool SocketImpl::getBlocking() const inline bool SocketImpl::getBlocking() const
{ {
return _blocking; return _blocking;

View File

@@ -1,7 +1,7 @@
// //
// SocketNotification.h // SocketNotification.h
// //
// $Id: //poco/1.3/Net/include/Poco/Net/SocketNotification.h#2 $ // $Id: //poco/Main/Net/include/Poco/Net/SocketNotification.h#4 $
// //
// Library: Net // Library: Net
// Package: Reactor // Package: Reactor
@@ -57,7 +57,7 @@ class Net_API SocketNotification: public Poco::Notification
/// the SocketReactor. /// the SocketReactor.
{ {
public: public:
SocketNotification(SocketReactor* pReactor); explicit SocketNotification(SocketReactor* pReactor);
/// Creates the SocketNotification for the given SocketReactor. /// Creates the SocketNotification for the given SocketReactor.
virtual ~SocketNotification(); virtual ~SocketNotification();

View File

@@ -1,7 +1,7 @@
// //
// SocketNotifier.h // SocketNotifier.h
// //
// $Id: //poco/svn/Net/include/Poco/Net/SocketNotifier.h#2 $ // $Id: //poco/Main/Net/include/Poco/Net/SocketNotifier.h#3 $
// //
// Library: Net // Library: Net
// Package: Reactor // Package: Reactor
@@ -62,7 +62,7 @@ class Net_API SocketNotifier: public Poco::RefCountedObject
/// to notify registered event handlers of socket events. /// to notify registered event handlers of socket events.
{ {
public: public:
SocketNotifier(const Socket& socket); explicit SocketNotifier(const Socket& socket);
/// Creates the SocketNotifier for the given socket. /// Creates the SocketNotifier for the given socket.
void addObserver(SocketReactor* pReactor, const Poco::AbstractObserver& observer); void addObserver(SocketReactor* pReactor, const Poco::AbstractObserver& observer);

View File

@@ -1,7 +1,7 @@
// //
// SocketReactor.h // SocketReactor.h
// //
// $Id: //poco/1.3/Net/include/Poco/Net/SocketReactor.h#2 $ // $Id: //poco/Main/Net/include/Poco/Net/SocketReactor.h#5 $
// //
// Library: Net // Library: Net
// Package: Reactor // Package: Reactor
@@ -132,7 +132,7 @@ public:
SocketReactor(); SocketReactor();
/// Creates the SocketReactor. /// Creates the SocketReactor.
SocketReactor(const Poco::Timespan& timeout); explicit SocketReactor(const Poco::Timespan& timeout);
/// Creates the SocketReactor, using the given timeout. /// Creates the SocketReactor, using the given timeout.
virtual ~SocketReactor(); virtual ~SocketReactor();

View File

@@ -1,7 +1,7 @@
// //
// SocketStream.h // SocketStream.h
// //
// $Id: //poco/svn/Net/include/Poco/Net/SocketStream.h#2 $ // $Id: //poco/Main/Net/include/Poco/Net/SocketStream.h#3 $
// //
// Library: Net // Library: Net
// Package: Sockets // Package: Sockets
@@ -121,7 +121,7 @@ class Net_API SocketOutputStream: public SocketIOS, public std::ostream
/// An output stream for writing to a socket. /// An output stream for writing to a socket.
{ {
public: public:
SocketOutputStream(const Socket& socket); explicit SocketOutputStream(const Socket& socket);
/// Creates the SocketOutputStream with the given socket. /// Creates the SocketOutputStream with the given socket.
/// ///
/// The socket's SocketImpl must be a StreamSocketImpl, /// The socket's SocketImpl must be a StreamSocketImpl,
@@ -147,7 +147,7 @@ class Net_API SocketInputStream: public SocketIOS, public std::istream
/// istream with formatted reads. /// istream with formatted reads.
{ {
public: public:
SocketInputStream(const Socket& socket); explicit SocketInputStream(const Socket& socket);
/// Creates the SocketInputStream with the given socket. /// Creates the SocketInputStream with the given socket.
/// ///
/// The socket's SocketImpl must be a StreamSocketImpl, /// The socket's SocketImpl must be a StreamSocketImpl,
@@ -171,7 +171,7 @@ class Net_API SocketStream: public SocketIOS, public std::iostream
/// istream with formatted reads. /// istream with formatted reads.
{ {
public: public:
SocketStream(const Socket& socket); explicit SocketStream(const Socket& socket);
/// Creates the SocketStream with the given socket. /// Creates the SocketStream with the given socket.
/// ///
/// The socket's SocketImpl must be a StreamSocketImpl, /// The socket's SocketImpl must be a StreamSocketImpl,

View File

@@ -1,7 +1,7 @@
// //
// StreamSocket.h // StreamSocket.h
// //
// $Id: //poco/svn/Net/include/Poco/Net/StreamSocket.h#2 $ // $Id: //poco/Main/Net/include/Poco/Net/StreamSocket.h#3 $
// //
// Library: Net // Library: Net
// Package: Sockets // Package: Sockets
@@ -62,7 +62,7 @@ public:
/// Before sending or receiving data, the socket /// Before sending or receiving data, the socket
/// must be connected with a call to connect(). /// must be connected with a call to connect().
StreamSocket(const SocketAddress& address); explicit StreamSocket(const SocketAddress& address);
/// Creates a stream socket and connects it to /// Creates a stream socket and connects it to
/// the socket specified by address. /// the socket specified by address.

View File

@@ -1,7 +1,7 @@
// //
// HTTPClientSession.cpp // HTTPClientSession.cpp
// //
// $Id: //poco/Main/Net/src/HTTPClientSession.cpp#20 $ // $Id: //poco/Main/Net/src/HTTPClientSession.cpp#21 $
// //
// Library: Net // Library: Net
// Package: HTTPClient // Package: HTTPClient
@@ -187,7 +187,7 @@ std::ostream& HTTPClientSession::sendRequest(HTTPRequest& request)
if (!request.has(HTTPRequest::HOST)) if (!request.has(HTTPRequest::HOST))
request.setHost(_host, _port); request.setHost(_host, _port);
if (!_proxyHost.empty()) if (!_proxyHost.empty())
request.setURI(getHostInfo() + request.getURI()); request.setURI(proxyRequestPrefix() + request.getURI());
_reconnect = keepAlive; _reconnect = keepAlive;
_expectResponseBody = request.getMethod() != HTTPRequest::HTTP_HEAD; _expectResponseBody = request.getMethod() != HTTPRequest::HTTP_HEAD;
if (request.getChunkedTransferEncoding()) if (request.getChunkedTransferEncoding())
@@ -203,7 +203,7 @@ std::ostream& HTTPClientSession::sendRequest(HTTPRequest& request)
_pRequestStream = new HTTPFixedLengthOutputStream(*this, request.getContentLength() + cs.chars()); _pRequestStream = new HTTPFixedLengthOutputStream(*this, request.getContentLength() + cs.chars());
request.write(*_pRequestStream); request.write(*_pRequestStream);
} }
else if (request.getMethod() == HTTPRequest::HTTP_GET || request.getMethod() == HTTPRequest::HTTP_HEAD) else if (request.getMethod() != HTTPRequest::HTTP_PUT && request.getMethod() != HTTPRequest::HTTP_POST)
{ {
Poco::CountingOutputStream cs; Poco::CountingOutputStream cs;
request.write(cs); request.write(cs);
@@ -296,7 +296,7 @@ void HTTPClientSession::reconnect()
} }
std::string HTTPClientSession::getHostInfo() const std::string HTTPClientSession::proxyRequestPrefix() const
{ {
std::string result("http://"); std::string result("http://");
result.append(_host); result.append(_host);

View File

@@ -1,7 +1,7 @@
// //
// HTTPServerResponseImpl.cpp // HTTPServerResponseImpl.cpp
// //
// $Id: //poco/Main/Net/src/HTTPServerResponseImpl.cpp#6 $ // $Id: //poco/Main/Net/src/HTTPServerResponseImpl.cpp#7 $
// //
// Library: Net // Library: Net
// Package: HTTPServer // Package: HTTPServer
@@ -154,7 +154,7 @@ void HTTPServerResponseImpl::redirect(const std::string& uri)
setStatusAndReason(HTTPResponse::HTTP_FOUND); setStatusAndReason(HTTPResponse::HTTP_FOUND);
set("Location", uri); set("Location", uri);
_pStream = new HTTPOutputStream(_session); _pStream = new HTTPHeaderOutputStream(_session);
write(*_pStream); write(*_pStream);
} }

View File

@@ -1,7 +1,7 @@
// //
// HTTPSession.cpp // HTTPSession.cpp
// //
// $Id: //poco/svn/Net/src/HTTPSession.cpp#2 $ // $Id: //poco/Main/Net/src/HTTPSession.cpp#14 $
// //
// Library: Net // Library: Net
// Package: HTTP // Package: HTTP
@@ -214,4 +214,19 @@ void HTTPSession::setException(const Poco::Exception& exc)
} }
StreamSocket HTTPSession::detachSocket()
{
StreamSocket oldSocket(_socket);
StreamSocket newSocket;
_socket = newSocket;
return oldSocket;
}
void HTTPSession::attachSocket(const StreamSocket& socket)
{
_socket = socket;
}
} } // namespace Poco::Net } } // namespace Poco::Net

View File

@@ -1,7 +1,7 @@
// //
// IPAddress.cpp // IPAddress.cpp
// //
// $Id: //poco/Main/Net/src/IPAddress.cpp#20 $ // $Id: //poco/Main/Net/src/IPAddress.cpp#21 $
// //
// Library: Net // Library: Net
// Package: NetCore // Package: NetCore
@@ -324,7 +324,7 @@ public:
} }
} }
if (i > 0) result.append(":"); if (i > 0) result.append(":");
if (i < 8) NumberFormatter::appendHex(result, ntohs(words[i++]))); if (i < 8) NumberFormatter::appendHex(result, ntohs(words[i++]));
} }
return result; return result;
} }

View File

@@ -1,7 +1,7 @@
// //
// SocketImpl.cpp // SocketImpl.cpp
// //
// $Id: //poco/svn/Net/src/SocketImpl.cpp#3 $ // $Id: //poco/Main/Net/src/SocketImpl.cpp#26 $
// //
// Library: Net // Library: Net
// Package: Sockets // Package: Sockets
@@ -338,6 +338,7 @@ int SocketImpl::available()
return result; return result;
} }
bool SocketImpl::poll(const Poco::Timespan& timeout, int mode) bool SocketImpl::poll(const Poco::Timespan& timeout, int mode)
{ {
#if defined(POCO_HAVE_FD_POLL) #if defined(POCO_HAVE_FD_POLL)
@@ -804,9 +805,8 @@ void SocketImpl::ioctl(int request, void* arg)
} }
void SocketImpl::setSockfd(poco_socket_t aSocket) void SocketImpl::reset(poco_socket_t aSocket)
{ {
poco_assert(sockfd() == POCO_INVALID_SOCKET);
_sockfd = aSocket; _sockfd = aSocket;
} }

View File

@@ -1,7 +1,7 @@
// //
// StreamSocket.cpp // StreamSocket.cpp
// //
// $Id: //poco/svn/Net/src/StreamSocket.cpp#2 $ // $Id: //poco/Main/Net/src/StreamSocket.cpp#9 $
// //
// Library: Net // Library: Net
// Package: Sockets // Package: Sockets

View File

@@ -1,7 +1,7 @@
// //
// StreamSocketImpl.cpp // StreamSocketImpl.cpp
// //
// $Id: //poco/svn/Net/src/StreamSocketImpl.cpp#2 $ // $Id: //poco/Main/Net/src/StreamSocketImpl.cpp#8 $
// //
// Library: Net // Library: Net
// Package: Sockets // Package: Sockets
@@ -62,7 +62,8 @@ int StreamSocketImpl::sendBytes(const void* buffer, int length, int flags)
int remaining = length; int remaining = length;
while (remaining > 0) while (remaining > 0)
{ {
int n = SocketImpl::sendBytes(p, remaining, flags); int n = SocketImpl::sendBytes(p, remaining, flags);
if (n <= 0) return n;
p += n; p += n;
remaining -= n; remaining -= n;
} }

View File

@@ -1,7 +1,7 @@
// //
// AcceptCertificateHandler.h // AcceptCertificateHandler.h
// //
// $Id: //poco/svn/NetSSL_OpenSSL/include/Poco/Net/AcceptCertificateHandler.h#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/include/Poco/Net/AcceptCertificateHandler.h#8 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
@@ -9,7 +9,7 @@
// //
// Definition of the AcceptCertificateHandler class. // Definition of the AcceptCertificateHandler class.
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -51,7 +51,9 @@ namespace Net {
class NetSSL_API AcceptCertificateHandler: public InvalidCertificateHandler class NetSSL_API AcceptCertificateHandler: public InvalidCertificateHandler
/// A AcceptCertificateHandler is invoked whenever an error /// A AcceptCertificateHandler is invoked whenever an error
/// occurs verifying the certificate. It always accepts /// occurs verifying the certificate. It always accepts
/// the certificate. Only use this one during testing! /// the certificate.
///
/// Should be using for testing purposes only.
{ {
public: public:
AcceptCertificateHandler(bool handleErrorsOnServerSide); AcceptCertificateHandler(bool handleErrorsOnServerSide);
@@ -66,15 +68,6 @@ public:
}; };
//
// inlines
//
inline void AcceptCertificateHandler::onInvalidCertificate(const void*, VerificationErrorArgs& errorCert)
{
errorCert.setIgnoreError(true);
}
} } // namespace Poco::Net } } // namespace Poco::Net

View File

@@ -1,7 +1,7 @@
// //
// CertificateHandlerFactory.h // CertificateHandlerFactory.h
// //
// $Id: //poco/svn/NetSSL_OpenSSL/include/Poco/Net/CertificateHandlerFactory.h#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/include/Poco/Net/CertificateHandlerFactory.h#8 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
@@ -9,7 +9,7 @@
// //
// Definition of the CertificateHandlerFactory class. // Definition of the CertificateHandlerFactory class.
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -52,6 +52,7 @@ class InvalidCertificateHandler;
class NetSSL_API CertificateHandlerFactory class NetSSL_API CertificateHandlerFactory
/// A CertificateHandlerFactory is responsible for creating InvalidCertificateHandlers. /// A CertificateHandlerFactory is responsible for creating InvalidCertificateHandlers.
///
/// You don't need to access this class directly. Use the macro /// You don't need to access this class directly. Use the macro
/// POCO_REGISTER_CHFACTORY(namespace, InvalidCertificateHandlerName) /// POCO_REGISTER_CHFACTORY(namespace, InvalidCertificateHandlerName)
/// instead (see the documentation of InvalidCertificateHandler for an example). /// instead (see the documentation of InvalidCertificateHandler for an example).
@@ -82,6 +83,7 @@ public:
/// Destroys the CertificateHandlerFactoryRegistrar. /// Destroys the CertificateHandlerFactoryRegistrar.
}; };
template <typename T> template <typename T>
class CertificateHandlerFactoryImpl: public Poco::Net::CertificateHandlerFactory class CertificateHandlerFactoryImpl: public Poco::Net::CertificateHandlerFactory
{ {

View File

@@ -1,7 +1,7 @@
// //
// CertificateHandlerFactoryMgr.h // CertificateHandlerFactoryMgr.h
// //
// $Id: //poco/svn/NetSSL_OpenSSL/include/Poco/Net/CertificateHandlerFactoryMgr.h#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/include/Poco/Net/CertificateHandlerFactoryMgr.h#7 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
@@ -9,7 +9,7 @@
// //
// Definition of the CertificateHandlerFactoryMgr class. // Definition of the CertificateHandlerFactoryMgr class.
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization

View File

@@ -1,7 +1,7 @@
// //
// ConsoleCertificateHandler.h // ConsoleCertificateHandler.h
// //
// $Id: //poco/svn/NetSSL_OpenSSL/include/Poco/Net/ConsoleCertificateHandler.h#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/include/Poco/Net/ConsoleCertificateHandler.h#7 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
@@ -9,7 +9,7 @@
// //
// Definition of the ConsoleCertificateHandler class. // Definition of the ConsoleCertificateHandler class.
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -49,7 +49,8 @@ namespace Net {
class NetSSL_API ConsoleCertificateHandler: public InvalidCertificateHandler class NetSSL_API ConsoleCertificateHandler: public InvalidCertificateHandler
/// A ConsoleCertificateHandler is invoked whenever an error occurs verifying the certificate. /// A ConsoleCertificateHandler is invoked whenever an error occurs verifying the certificate.
///
/// The certificate is printed to stdout and the user is asked via console if he wants to accept it. /// The certificate is printed to stdout and the user is asked via console if he wants to accept it.
{ {
public: public:

View File

@@ -1,7 +1,7 @@
// //
// Context.h // Context.h
// //
// $Id: //poco/1.3/NetSSL_OpenSSL/include/Poco/Net/Context.h#3 $ // $Id: //poco/Main/NetSSL_OpenSSL/include/Poco/Net/Context.h#9 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
@@ -9,7 +9,7 @@
// //
// Definition of the Context class. // Definition of the Context class.
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -41,7 +41,8 @@
#include "Poco/Net/NetSSL.h" #include "Poco/Net/NetSSL.h"
#include "Poco/SharedPtr.h" #include "Poco/RefCountedObject.h"
#include "Poco/AutoPtr.h"
#include <openssl/ssl.h> #include <openssl/ssl.h>
@@ -49,60 +50,110 @@ namespace Poco {
namespace Net { namespace Net {
class NetSSL_API Context class NetSSL_API Context: public Poco::RefCountedObject
/// This class encapsulates an SSL Context. /// This class encapsulates context information for
/// an SSL server or client, such as the certificate
/// verification mode and the location of certificates
/// and private key files, as well as the list of
/// supported ciphers.
{ {
public: public:
typedef Poco::SharedPtr<Context> Ptr; typedef Poco::AutoPtr<Context> Ptr;
enum Usage
{
CLIENT_USE, /// Context is used by a client.
SERVER_USE /// Context is used by a server.
};
enum VerificationMode enum VerificationMode
{ {
VERIFY_NONE = SSL_VERIFY_NONE, VERIFY_NONE = SSL_VERIFY_NONE,
/// Server: The server will not send a client certificate
/// request to the client, so the client will not send a certificate.
///
/// Client: If not using an anonymous cipher (by default disabled),
/// the server will send a certificate which will be checked, but
/// the result of the check will be ignored.
VERIFY_RELAXED = SSL_VERIFY_PEER, VERIFY_RELAXED = SSL_VERIFY_PEER,
VERIFY_STRICT = SSL_VERIFY_FAIL_IF_NO_PEER_CERT, /// Server: The server sends a client certificate request to the
VERIFY_ONCE = SSL_VERIFY_CLIENT_ONCE /// client. The certificate returned (if any) is checked.
/// If the verification process fails, the TLS/SSL handshake is
/// immediately terminated with an alert message containing the
/// reason for the verification failure.
///
/// Client: The server certificate is verified, if one is provided.
/// If the verification process fails, the TLS/SSL handshake is
/// immediately terminated with an alert message containing the
/// reason for the verification failure.
VERIFY_STRICT = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
/// Server: If the client did not return a certificate, the TLS/SSL
/// handshake is immediately terminated with a handshake failure
/// alert. This flag must be used together with SSL_VERIFY_PEER.
///
/// Client: Same as VERIFY_RELAXED.
VERIFY_ONCE = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE
/// Server: Only request a client certificate on the initial
/// TLS/SSL handshake. Do not ask for a client certificate
/// again in case of a renegotiation.
///
/// Client: Same as VERIFY_RELAXED.
}; };
Context(const std::string& privateKeyFile, Context(
Usage usage,
const std::string& privateKeyFile,
const std::string& certificateFile,
const std::string& caLocation, const std::string& caLocation,
bool isServerContext, VerificationMode verificationMode = VERIFY_RELAXED,
VerificationMode verMode = VERIFY_STRICT,
int verificationDepth = 9, int verificationDepth = 9,
bool loadCAFromDefaultPath = false, bool loadDefaultCAs = false,
const std::string& cypherList = "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); const std::string& cipherList = "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
/// Creates a context. /// Creates a Context.
/// privateKeyFile contains the key used for encryption, caLocation can either ///
/// be a directory or a single file containing the certificates for certificate authorities. /// * usage specifies whether the context is used by a client or server.
/// isServerContext defines if the context belongs to a server or client. /// * privateKeyFile contains the path to the private key file used for encryption.
/// verificationDepth sets the upper limit for verification chain sizes. If we encounter /// Can be empty if no private key file is used.
/// a chain larger than that limit, verification will fail. /// * certificateFile contains the path to the certificate file (in PEM format).
/// Cypherlist defines which protocols are allowed. /// If the private key and the certificate are stored in the same file, this
/// Creates the Context. /// can be empty if privateKeyFile is given.
/// * caLocation contains the path to the file or directory containing the
/// CA/root certificates. Can be empty if the OpenSSL builtin CA certificates
/// are used (see loadDefaultCAs).
/// * verificationMode specifies whether and how peer certificates are validated.
/// * verificationDepth sets the upper limit for verification chain sizes. Verification
/// will fail if a certificate chain larger than this is encountered.
/// * loadDefaultCAs specifies wheter the builtin CA certificates from OpenSSL are used.
/// * cipherList specifies the supported ciphers in OpenSSL notation.
~Context(); ~Context();
/// Destroys the Context. /// Destroys the Context.
SSL_CTX* sslContext() const; SSL_CTX* sslContext() const;
/// Returns the OpenSSL SSL Context object. /// Returns the underlying OpenSSL SSL Context object.
Usage usage() const;
/// Returns whether the context is for use by a client or by a server.
Context::VerificationMode verificationMode() const; Context::VerificationMode verificationMode() const;
/// Returns the verification mode. /// Returns the verification mode.
bool serverContext() const;
/// Returns true iff the context is for a server.
private: private:
SSL_CTX* _pSSLContext; Usage _usage;
Context::VerificationMode _mode; VerificationMode _mode;
bool _server; SSL_CTX* _pSSLContext;
}; };
// //
// inlines // inlines
// //
inline SSL_CTX* Context::sslContext() const inline Context::Usage Context::usage() const
{ {
return _pSSLContext; return _usage;
} }
@@ -112,9 +163,9 @@ inline Context::VerificationMode Context::verificationMode() const
} }
inline bool Context::serverContext() const inline SSL_CTX* Context::sslContext() const
{ {
return _server; return _pSSLContext;
} }

View File

@@ -1,7 +1,7 @@
// //
// HTTPSClientSession.h // HTTPSClientSession.h
// //
// $Id: //poco/svn/NetSSL_OpenSSL/include/Poco/Net/HTTPSClientSession.h#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/include/Poco/Net/HTTPSClientSession.h#9 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: HTTPSClient // Package: HTTPSClient
@@ -9,7 +9,7 @@
// //
// Definition of the HTTPSClientSession class. // Definition of the HTTPSClientSession class.
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -43,6 +43,8 @@
#include "Poco/Net/NetSSL.h" #include "Poco/Net/NetSSL.h"
#include "Poco/Net/Utility.h" #include "Poco/Net/Utility.h"
#include "Poco/Net/HTTPClientSession.h" #include "Poco/Net/HTTPClientSession.h"
#include "Poco/Net/Context.h"
#include "Poco/Net/X509Certificate.h"
namespace Poco { namespace Poco {
@@ -76,33 +78,56 @@ class NetSSL_API HTTPSClientSession: public HTTPClientSession
/// ///
/// See RFC 2616 <http://www.faqs.org/rfcs/rfc2616.html> for more /// See RFC 2616 <http://www.faqs.org/rfcs/rfc2616.html> for more
/// information about the HTTP protocol. /// information about the HTTP protocol.
///
/// Note that sending requests that neither contain a content length
/// field in the header nor are using chunked transfer encoding will
/// result in a SSL protocol violation, as the framework shuts down
/// the socket after sending the message body. No orderly SSL shutdown
/// will be performed in this case.
{ {
public: public:
enum
{
HTTPS_PORT = 443
};
HTTPSClientSession(); HTTPSClientSession();
/// Creates an unconnected HTTPSClientSession. /// Creates an unconnected HTTPSClientSession.
HTTPSClientSession(const SecureStreamSocket& socket); explicit HTTPSClientSession(const SecureStreamSocket& socket);
/// Creates a HTTPSClientSession using the given socket. /// Creates a HTTPSClientSession using the given socket.
/// The socket must not be connected. The session /// The socket must not be connected. The session
/// takes ownership of the socket. /// takes ownership of the socket.
HTTPSClientSession(const std::string& host, Poco::UInt16 port = Utility::HTTPS_PORT); HTTPSClientSession(const std::string& host, Poco::UInt16 port = HTTPS_PORT);
/// Creates a HTTPSClientSession using the given host and port. /// Creates a HTTPSClientSession using the given host and port.
explicit HTTPSClientSession(Context::Ptr pContext);
/// Creates an unconnected HTTPSClientSession, using the
/// give SSL context.
HTTPSClientSession(const std::string& host, Poco::UInt16 port, Context::Ptr pContext);
/// Creates a HTTPSClientSession using the given host and port,
/// using the given SSL context.
~HTTPSClientSession(); ~HTTPSClientSession();
/// Destroys the HTTPSClientSession and closes /// Destroys the HTTPSClientSession and closes
/// the underlying socket. /// the underlying socket.
X509Certificate serverCertificate();
/// Returns the server's certificate.
///
/// The certificate is available after the first request has been sent.
protected: protected:
void connect(const SocketAddress& address); void connect(const SocketAddress& address);
// Connects the socket to the server. std::string proxyRequestPrefix() const;
std::string getHostInfo() const;
/// Returns the target host and port number for proxy requests.
private: private:
HTTPSClientSession(const HTTPSClientSession&); HTTPSClientSession(const HTTPSClientSession&);
HTTPSClientSession& operator = (const HTTPSClientSession&); HTTPSClientSession& operator = (const HTTPSClientSession&);
Context::Ptr _pContext;
}; };

View File

@@ -1,7 +1,7 @@
// //
// HTTPSSessionInstantiator.h // HTTPSSessionInstantiator.h
// //
// $Id: //poco/svn/NetSSL_OpenSSL/include/Poco/Net/HTTPSSessionInstantiator.h#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/include/Poco/Net/HTTPSSessionInstantiator.h#7 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: HTTPSClient // Package: HTTPSClient
@@ -9,7 +9,7 @@
// //
// Definition of the HTTPSSessionInstantiator class. // Definition of the HTTPSSessionInstantiator class.
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization

View File

@@ -1,7 +1,7 @@
// //
// HTTPSStreamFactory.h // HTTPSStreamFactory.h
// //
// $Id: //poco/svn/NetSSL_OpenSSL/include/Poco/Net/HTTPSStreamFactory.h#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/include/Poco/Net/HTTPSStreamFactory.h#7 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: HTTPSClient // Package: HTTPSClient
@@ -9,7 +9,7 @@
// //
// Definition of the HTTPSStreamFactory class. // Definition of the HTTPSStreamFactory class.
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -51,7 +51,7 @@ namespace Net {
class NetSSL_API HTTPSStreamFactory: public Poco::URIStreamFactory class NetSSL_API HTTPSStreamFactory: public Poco::URIStreamFactory
/// An implementation of the URIStreamFactory interface /// An implementation of the URIStreamFactory interface
/// that handles Hyper-Text Transfer Protocol (http) URIs. /// that handles secure Hyper-Text Transfer Protocol (https) URIs.
{ {
public: public:
HTTPSStreamFactory(); HTTPSStreamFactory();

View File

@@ -1,7 +1,7 @@
// //
// InvalidCertificateHandler.h // InvalidCertificateHandler.h
// //
// $Id: //poco/svn/NetSSL_OpenSSL/include/Poco/Net/InvalidCertificateHandler.h#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/include/Poco/Net/InvalidCertificateHandler.h#7 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
@@ -9,7 +9,7 @@
// //
// Definition of the InvalidCertificateHandler class. // Definition of the InvalidCertificateHandler class.
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -52,7 +52,7 @@ class NetSSL_API InvalidCertificateHandler
/// A InvalidCertificateHandler is invoked whenever an error occurs verifying the certificate. It allows the user /// A InvalidCertificateHandler is invoked whenever an error occurs verifying the certificate. It allows the user
/// to inspect and accept/reject the certificate. /// to inspect and accept/reject the certificate.
/// One can install one's own InvalidCertificateHandler by implementing this interface. Note that /// One can install one's own InvalidCertificateHandler by implementing this interface. Note that
/// in the cpp file of the subclass the following code must be present (assuming you use the namespace My_API /// in the implementation file of the subclass the following code must be present (assuming you use the namespace My_API
/// and the name of your handler class is MyGuiHandler): /// and the name of your handler class is MyGuiHandler):
/// ///
/// #include "Poco/Net/CertificateHandlerFactory.h" /// #include "Poco/Net/CertificateHandlerFactory.h"
@@ -72,11 +72,13 @@ class NetSSL_API InvalidCertificateHandler
/// [...] // Put optional config params for the handler here /// [...] // Put optional config params for the handler here
/// </options> /// </options>
/// </invalidCertificateHandler> /// </invalidCertificateHandler>
///
/// Note that the name of the InvalidCertificateHandler must be same as the one provided to the POCO_REGISTER_CHFACTORY macro. /// Note that the name of the InvalidCertificateHandler must be same as the one provided to the POCO_REGISTER_CHFACTORY macro.
{ {
public: public:
InvalidCertificateHandler(bool handleErrorsOnServerSide); InvalidCertificateHandler(bool handleErrorsOnServerSide);
/// Creates the InvalidCertificateHandler. /// Creates the InvalidCertificateHandler.
///
/// Set handleErrorsOnServerSide to true if the certificate handler is used on the server side. /// Set handleErrorsOnServerSide to true if the certificate handler is used on the server side.
/// Automatically registers at one of the SSLManager::VerificationError events. /// Automatically registers at one of the SSLManager::VerificationError events.

View File

@@ -1,7 +1,7 @@
// //
// KeyConsoleHandler.h // KeyConsoleHandler.h
// //
// $Id: //poco/svn/NetSSL_OpenSSL/include/Poco/Net/KeyConsoleHandler.h#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/include/Poco/Net/KeyConsoleHandler.h#7 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
@@ -9,7 +9,7 @@
// //
// Definition of the KeyConsoleHandler class. // Definition of the KeyConsoleHandler class.
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -49,7 +49,8 @@ namespace Net {
class NetSSL_API KeyConsoleHandler: public PrivateKeyPassphraseHandler class NetSSL_API KeyConsoleHandler: public PrivateKeyPassphraseHandler
/// Class KeyConsoleHandler. Reads the key for a certificate from the console. /// An implementation of PrivateKeyPassphraseHandler that
/// reads the key for a certificate from the console.
{ {
public: public:
KeyConsoleHandler(bool server); KeyConsoleHandler(bool server);

View File

@@ -1,7 +1,7 @@
// //
// KeyFileHandler.h // KeyFileHandler.h
// //
// $Id: //poco/svn/NetSSL_OpenSSL/include/Poco/Net/KeyFileHandler.h#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/include/Poco/Net/KeyFileHandler.h#7 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
@@ -9,7 +9,7 @@
// //
// Definition of the KeyFileHandler class. // Definition of the KeyFileHandler class.
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -49,7 +49,8 @@ namespace Net {
class NetSSL_API KeyFileHandler: public PrivateKeyPassphraseHandler class NetSSL_API KeyFileHandler: public PrivateKeyPassphraseHandler
/// Class KeyFileHandler. Reads the key for a certificate from a configuration file /// An implementation of PrivateKeyPassphraseHandler that
/// reads the key for a certificate from a configuration file
/// under the path "openSSL.privateKeyPassphraseHandler.options.password". /// under the path "openSSL.privateKeyPassphraseHandler.options.password".
{ {
public: public:

View File

@@ -1,7 +1,7 @@
// //
// NetSSL.h // NetSSL.h
// //
// $Id: //poco/svn/NetSSL_OpenSSL/include/Poco/Net/NetSSL.h#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/include/Poco/Net/NetSSL.h#8 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
@@ -11,7 +11,7 @@
// This file must be the first file included by every other OpenSSL // This file must be the first file included by every other OpenSSL
// header file. // header file.
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization

View File

@@ -1,7 +1,7 @@
// //
// PrivateKeyFactory.h // PrivateKeyFactory.h
// //
// $Id: //poco/svn/NetSSL_OpenSSL/include/Poco/Net/PrivateKeyFactory.h#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/include/Poco/Net/PrivateKeyFactory.h#8 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
@@ -9,7 +9,7 @@
// //
// Definition of the PrivateKeyFactory class. // Definition of the PrivateKeyFactory class.
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -52,6 +52,7 @@ class PrivateKeyPassphraseHandler;
class NetSSL_API PrivateKeyFactory class NetSSL_API PrivateKeyFactory
/// A PrivateKeyFactory is responsible for creating PrivateKeyPassphraseHandlers. /// A PrivateKeyFactory is responsible for creating PrivateKeyPassphraseHandlers.
///
/// You don't need to access this class directly. Use the macro /// You don't need to access this class directly. Use the macro
/// POCO_REGISTER_KEYFACTORY(namespace, PrivateKeyPassphraseHandlerName) /// POCO_REGISTER_KEYFACTORY(namespace, PrivateKeyPassphraseHandlerName)
/// instead (see the documentation of PrivateKeyPassphraseHandler for an example). /// instead (see the documentation of PrivateKeyPassphraseHandler for an example).
@@ -70,6 +71,7 @@ public:
class NetSSL_API PrivateKeyFactoryRegistrar class NetSSL_API PrivateKeyFactoryRegistrar
/// Registrar class which automatically registers PrivateKeyFactories at the PrivateKeyFactoryMgr. /// Registrar class which automatically registers PrivateKeyFactories at the PrivateKeyFactoryMgr.
///
/// You don't need to access this class directly. Use the macro /// You don't need to access this class directly. Use the macro
/// POCO_REGISTER_KEYFACTORY(namespace, PrivateKeyPassphraseHandlerName) /// POCO_REGISTER_KEYFACTORY(namespace, PrivateKeyPassphraseHandlerName)
/// instead (see the documentation of PrivateKeyPassphraseHandler for an example). /// instead (see the documentation of PrivateKeyPassphraseHandler for an example).

View File

@@ -1,7 +1,7 @@
// //
// PrivateKeyFactoryMgr.h // PrivateKeyFactoryMgr.h
// //
// $Id: //poco/svn/NetSSL_OpenSSL/include/Poco/Net/PrivateKeyFactoryMgr.h#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/include/Poco/Net/PrivateKeyFactoryMgr.h#7 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
@@ -9,7 +9,7 @@
// //
// Definition of the PrivateKeyFactoryMgr class. // Definition of the PrivateKeyFactoryMgr class.
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization

View File

@@ -1,7 +1,7 @@
// //
// PrivateKeyPassphraseHandler.h // PrivateKeyPassphraseHandler.h
// //
// $Id: //poco/svn/NetSSL_OpenSSL/include/Poco/Net/PrivateKeyPassphraseHandler.h#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/include/Poco/Net/PrivateKeyPassphraseHandler.h#7 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
@@ -9,7 +9,7 @@
// //
// Definition of the PrivateKeyPassphraseHandler class. // Definition of the PrivateKeyPassphraseHandler class.
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -51,7 +51,7 @@ class NetSSL_API PrivateKeyPassphraseHandler
/// A passphrase handler is needed whenever the private key of a certificate is loaded and the certificate is protected /// A passphrase handler is needed whenever the private key of a certificate is loaded and the certificate is protected
/// by a passphrase. The PrivateKeyPassphraseHandler's task is to provide that passphrase. /// by a passphrase. The PrivateKeyPassphraseHandler's task is to provide that passphrase.
/// One can install one's own PrivateKeyPassphraseHandler by implementing this interface. Note that /// One can install one's own PrivateKeyPassphraseHandler by implementing this interface. Note that
/// in the cpp file of the subclass the following code must be present (assuming you use the namespace My_API /// in the implementation file of the subclass the following code must be present (assuming you use the namespace My_API
/// and the name of your handler class is MyGuiHandler): /// and the name of your handler class is MyGuiHandler):
/// ///
/// #include "Poco/Net/PrivateKeyFactory.h" /// #include "Poco/Net/PrivateKeyFactory.h"
@@ -71,6 +71,7 @@ class NetSSL_API PrivateKeyPassphraseHandler
/// [...] // Put optional config params for the handler here /// [...] // Put optional config params for the handler here
/// </options> /// </options>
/// </privateKeyPassphraseHandler> /// </privateKeyPassphraseHandler>
///
/// Note that the name of the passphrase handler must be same as the one provided to the POCO_REGISTER_KEYFACTORY macro. /// Note that the name of the passphrase handler must be same as the one provided to the POCO_REGISTER_KEYFACTORY macro.
{ {
public: public:

View File

@@ -1,7 +1,7 @@
// //
// SSLException.h // SSLException.h
// //
// $Id: //poco/svn/NetSSL_OpenSSL/include/Poco/Net/SSLException.h#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/include/Poco/Net/SSLException.h#7 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
@@ -9,7 +9,7 @@
// //
// Definition of the SSLException class. // Definition of the SSLException class.
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -51,6 +51,7 @@ namespace Net {
POCO_DECLARE_EXCEPTION(NetSSL_API, SSLException, NetException) POCO_DECLARE_EXCEPTION(NetSSL_API, SSLException, NetException)
POCO_DECLARE_EXCEPTION(NetSSL_API, SSLContextException, SSLException) POCO_DECLARE_EXCEPTION(NetSSL_API, SSLContextException, SSLException)
POCO_DECLARE_EXCEPTION(NetSSL_API, InvalidCertificateException, SSLException) POCO_DECLARE_EXCEPTION(NetSSL_API, InvalidCertificateException, SSLException)
POCO_DECLARE_EXCEPTION(NetSSL_API, CertificateValidationException, SSLException)
} } // namespace Poco::Net } } // namespace Poco::Net

View File

@@ -1,7 +1,7 @@
// //
// SSLInitializer.h // SSLInitializer.h
// //
// $Id: //poco/svn/NetSSL_OpenSSL/include/Poco/Net/SSLInitializer.h#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/include/Poco/Net/SSLInitializer.h#7 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
@@ -9,7 +9,7 @@
// //
// Definition of the SSLInitializer class. // Definition of the SSLInitializer class.
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization

View File

@@ -1,7 +1,7 @@
// //
// SSLManager.h // SSLManager.h
// //
// $Id: //poco/svn/NetSSL_OpenSSL/include/Poco/Net/SSLManager.h#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/include/Poco/Net/SSLManager.h#7 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
@@ -9,7 +9,7 @@
// //
// Definition of the SSLManager class. // Definition of the SSLManager class.
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -59,19 +59,23 @@ class Context;
class NetSSL_API SSLManager class NetSSL_API SSLManager
/// Class SSLManager. Singleton for holding the default server/client Context and PrivateKeyPassphraseHandler. /// SSLManager is a singleton for holding the default server/client
/// Context and PrivateKeyPassphraseHandler.
///
/// Either initialize via Poco::Util::Application or via the /// Either initialize via Poco::Util::Application or via the
/// initialize methods of the singleton. Note that the latter initialization must happen very early /// initialize methods of the singleton. Note that the latter initialization must happen very early
/// during program startup before somebody calls defaultClientContext()/defaultServerContext() /// during program startup before somebody calls defaultClientContext()/defaultServerContext()
/// or any of the passPhraseHandler methods (which tries to auto-initialize /// or any of the passPhraseHandler methods (which tries to auto-initialize
/// the context and passphrase handler based on an Poco::Util::Application configuration). /// the context and passphrase handler based on an Poco::Util::Application configuration).
///
/// An exemplary documentation which sets either the server or client defaultcontext and creates a PrivateKeyPassphraseHandler /// An exemplary documentation which sets either the server or client defaultcontext and creates a PrivateKeyPassphraseHandler
/// that reads the password from the XML file looks like this: /// that reads the password from the XML file looks like this:
/// ///
/// <AppConfig> /// <AppConfig>
/// <openSSL> /// <openSSL>
/// <server|client> /// <server|client>
/// <privateKeyFile>any.pem</privateKeyFile> /// <privateKeyFile>mycert.key</privateKeyFile>
/// <certificateFile>mycert.crt</certificateFile>
/// <caConfig>rootcert.pem</caConfig> /// <caConfig>rootcert.pem</caConfig>
/// <verificationMode>relaxed</verificationMode> /// <verificationMode>relaxed</verificationMode>
/// <verificationDepth>9</verificationDepth> /// <verificationDepth>9</verificationDepth>
@@ -91,56 +95,59 @@ class NetSSL_API SSLManager
/// </server|client> /// </server|client>
/// </openSSL> /// </openSSL>
/// </AppConfig> /// </AppConfig>
///
{ {
public: public:
typedef Poco::SharedPtr<Context> ContextPtr;
typedef Poco::SharedPtr<PrivateKeyPassphraseHandler> PrivateKeyPassphraseHandlerPtr; typedef Poco::SharedPtr<PrivateKeyPassphraseHandler> PrivateKeyPassphraseHandlerPtr;
typedef Poco::SharedPtr<InvalidCertificateHandler> InvalidCertificateHandlerPtr; typedef Poco::SharedPtr<InvalidCertificateHandler> InvalidCertificateHandlerPtr;
Poco::BasicEvent<VerificationErrorArgs> ServerVerificationError; Poco::BasicEvent<VerificationErrorArgs> ServerVerificationError;
/// Thrown whenever a certificate error is detected by the server during a handshake /// Thrown whenever a certificate error is detected by the server during a handshake.
Poco::BasicEvent<VerificationErrorArgs> ClientVerificationError; Poco::BasicEvent<VerificationErrorArgs> ClientVerificationError;
/// Thrown whenever a certificate error is detected by the client during a handshake /// Thrown whenever a certificate error is detected by the client during a handshake.
Poco::BasicEvent<std::string> PrivateKeyPassPhrase; Poco::BasicEvent<std::string> PrivateKeyPassPhrase;
/// Thrown when a encrypted certificate is loaded. Not setting the passwd /// Thrown when a encrypted certificate is loaded. Not setting the password
/// in the event parameter will result in a failure to load the certificate. /// in the event parameter will result in a failure to load the certificate.
///
/// Per default the SSLManager checks the configuration.xml file (path openSSL.privateKeyPassphraseHandler.name) /// Per default the SSLManager checks the configuration.xml file (path openSSL.privateKeyPassphraseHandler.name)
/// which default delegate it should register. If nothing is configured, /// for which default delegate it should register. If nothing is configured,
/// a KeyConsoleHandler is used. /// a KeyConsoleHandler is used.
static SSLManager& instance(); static SSLManager& instance();
/// Returns the instance of the SSLManager singleton. /// Returns the instance of the SSLManager singleton.
void initializeServer(PrivateKeyPassphraseHandlerPtr& ptrPassPhraseHandler, InvalidCertificateHandlerPtr& ptrHandler, ContextPtr ptrContext); void initializeServer(PrivateKeyPassphraseHandlerPtr ptrPassPhraseHandler, InvalidCertificateHandlerPtr ptrHandler, Context::Ptr ptrContext);
/// Initializes the server side of the SSLManager with a default passphrase handler, a default invalid certificate handler and a default context. If this method /// Initializes the server side of the SSLManager with a default passphrase handler, a default invalid certificate handler and a default context. If this method
/// is never called the SSLmanager will try to initialize its members from an application configuration. /// is never called the SSLmanager will try to initialize its members from an application configuration.
///
/// Note: ALWAYS create the handlers before you create the context! /// Note: ALWAYS create the handlers before you create the context!
///
/// Valid initialization code would be: /// Valid initialization code would be:
/// SharedPtr<PrivateKeyPassphraseHandler> ptrConsole = new KeyConsoleHandler(); /// SharedPtr<PrivateKeyPassphraseHandler> ptrConsole = new KeyConsoleHandler();
/// SharedPtr<InvalidCertificateHandler> ptrCert = new ConsoleCertificateHandler(); /// SharedPtr<InvalidCertificateHandler> ptrCert = new ConsoleCertificateHandler();
/// SharedPtr<Context> ptrContext = new Context("any.pem", "rootcert.pem", Context::Relaxed, 9, false, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); /// Context::Ptr ptrContext = new Context("any.pem", "rootcert.pem", Context::Relaxed, 9, false, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
/// ///
/// This method can only be called, if no defaultContext is set yet. /// This method can only be called if no defaultContext is set yet.
void initializeClient(PrivateKeyPassphraseHandlerPtr& ptrPassPhraseHandler, InvalidCertificateHandlerPtr& ptrHandler, ContextPtr ptrContext); void initializeClient(PrivateKeyPassphraseHandlerPtr ptrPassPhraseHandler, InvalidCertificateHandlerPtr ptrHandler, Context::Ptr ptrContext);
/// Initializes the client side of the SSLManager with a default passphrase handler, a default invalid certificate handler and a default context. If this method /// Initializes the client side of the SSLManager with a default passphrase handler, a default invalid certificate handler and a default context. If this method
/// is never called the SSLmanager will try to initialize its members from an application configuration. /// is never called the SSLmanager will try to initialize its members from an application configuration.
///
/// Note: ALWAYS create the handlers before you create the context! /// Note: ALWAYS create the handlers before you create the context!
///
/// Valid initialization code would be: /// Valid initialization code would be:
/// SharedPtr<PrivateKeyPassphraseHandler> ptrConsole = new KeyConsoleHandler(); /// SharedPtr<PrivateKeyPassphraseHandler> ptrConsole = new KeyConsoleHandler();
/// SharedPtr<InvalidCertificateHandler> ptrCert = new ConsoleCertificateHandler(); /// SharedPtr<InvalidCertificateHandler> ptrCert = new ConsoleCertificateHandler();
/// SharedPtr<Context> ptrContext = new Context("any.pem", "rootcert.pem", Context::Relaxed, 9, false, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); /// Context::Ptr ptrContext = new Context("any.pem", "rootcert.pem", Context::Relaxed, 9, false, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
/// ///
/// This method can only be called, if no defaultContext is set yet. /// This method can only be called if no defaultContext is set yet.
ContextPtr defaultServerContext(); Context::Ptr defaultServerContext();
/// Returns the default context used by the server. The first call to this method initializes the defaultContext /// Returns the default context used by the server. The first call to this method initializes the defaultContext
/// from an application configuration. /// from an application configuration.
ContextPtr defaultClientContext(); Context::Ptr defaultClientContext();
/// Returns the default context used by the client. The first call to this method initializes the defaultContext /// Returns the default context used by the client. The first call to this method initializes the defaultContext
/// from an application configuration. /// from an application configuration.
@@ -168,6 +175,10 @@ public:
/// Returns the CertificateHandlerFactoryMgr which stores the /// Returns the CertificateHandlerFactoryMgr which stores the
/// factories for the different registered certificate handlers. /// factories for the different registered certificate handlers.
static const std::string CFG_SERVER_PREFIX;
static const std::string CFG_CLIENT_PREFIX;
protected:
static int verifyClientCallback(int ok, X509_STORE_CTX* pStore); static int verifyClientCallback(int ok, X509_STORE_CTX* pStore);
/// The return value of this method defines how errors in /// The return value of this method defines how errors in
/// verification are handled. Return 0 to terminate the handshake, /// verification are handled. Return 0 to terminate the handshake,
@@ -179,13 +190,10 @@ public:
/// or 1 to continue despite the error. /// or 1 to continue despite the error.
static int privateKeyPasswdCallback(char* pBuf, int size, int flag, void* userData); static int privateKeyPasswdCallback(char* pBuf, int size, int flag, void* userData);
/// Method is invoked by OpenSSl to retrieve a passwd for an encrypted certificate. /// Method is invoked by OpenSSL to retrieve a passwd for an encrypted certificate.
/// The request is delegated to the PrivatekeyPassword event. This method returns the /// The request is delegated to the PrivatekeyPassword event. This method returns the
/// length of the password. /// length of the password.
static const std::string CFG_SERVER_PREFIX;
static const std::string CFG_CLIENT_PREFIX;
private: private:
SSLManager(); SSLManager();
/// Creates the SSLManager. /// Creates the SSLManager.
@@ -212,14 +220,15 @@ private:
PrivateKeyFactoryMgr _factoryMgr; PrivateKeyFactoryMgr _factoryMgr;
CertificateHandlerFactoryMgr _certHandlerFactoryMgr; CertificateHandlerFactoryMgr _certHandlerFactoryMgr;
ContextPtr _ptrDefaultServerContext; Context::Ptr _ptrDefaultServerContext;
PrivateKeyPassphraseHandlerPtr _ptrServerPassPhraseHandler; PrivateKeyPassphraseHandlerPtr _ptrServerPassPhraseHandler;
InvalidCertificateHandlerPtr _ptrServerCertificateHandler; InvalidCertificateHandlerPtr _ptrServerCertificateHandler;
ContextPtr _ptrDefaultClientContext; Context::Ptr _ptrDefaultClientContext;
PrivateKeyPassphraseHandlerPtr _ptrClientPassPhraseHandler; PrivateKeyPassphraseHandlerPtr _ptrClientPassPhraseHandler;
InvalidCertificateHandlerPtr _ptrClientCertificateHandler; InvalidCertificateHandlerPtr _ptrClientCertificateHandler;
static const std::string CFG_PRIV_KEY_FILE; static const std::string CFG_PRIV_KEY_FILE;
static const std::string CFG_CERTIFICATE_FILE;
static const std::string CFG_CA_LOCATION; static const std::string CFG_CA_LOCATION;
static const std::string CFG_VER_MODE; static const std::string CFG_VER_MODE;
static const Context::VerificationMode VAL_VER_MODE; static const Context::VerificationMode VAL_VER_MODE;
@@ -235,6 +244,7 @@ private:
static const std::string VAL_CERTIFICATE_HANDLER; static const std::string VAL_CERTIFICATE_HANDLER;
friend class Poco::SingletonHolder<SSLManager>; friend class Poco::SingletonHolder<SSLManager>;
friend class Context;
}; };

View File

@@ -1,7 +1,7 @@
// //
// SecureServerSocket.h // SecureServerSocket.h
// //
// $Id: //poco/svn/NetSSL_OpenSSL/include/Poco/Net/SecureServerSocket.h#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/include/Poco/Net/SecureServerSocket.h#7 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLSockets // Package: SSLSockets
@@ -9,7 +9,7 @@
// //
// Definition of the SecureServerSocket class. // Definition of the SecureServerSocket class.
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -42,6 +42,7 @@
#include "Poco/Net/NetSSL.h" #include "Poco/Net/NetSSL.h"
#include "Poco/Net/ServerSocket.h" #include "Poco/Net/ServerSocket.h"
#include "Poco/Net/Context.h"
namespace Poco { namespace Poco {
@@ -53,7 +54,15 @@ class NetSSL_API SecureServerSocket: public ServerSocket
{ {
public: public:
SecureServerSocket(); SecureServerSocket();
/// Creates a SSL server socket. /// Creates a SSL server socket using the
/// default SSL server context.
///
/// The server socket must be bound to
/// an address and put into listening state.
explicit SecureServerSocket(Context::Ptr pContext);
/// Creates a SSL server socket, using the
/// given SSL context object.
/// ///
/// The server socket must be bound to /// The server socket must be bound to
/// an address and put into listening state. /// an address and put into listening state.
@@ -61,11 +70,19 @@ public:
SecureServerSocket(const Socket& socket); SecureServerSocket(const Socket& socket);
/// Creates the SecureServerSocket with the SocketImpl /// Creates the SecureServerSocket with the SocketImpl
/// from another socket. The SocketImpl must be /// from another socket. The SocketImpl must be
/// a ServerSocketImpl, otherwise an InvalidArgumentException /// a SecureServerSocketImpl, otherwise an InvalidArgumentException
/// will be thrown. /// will be thrown.
SecureServerSocket(const SocketAddress& address, int backlog = 64); SecureServerSocket(const SocketAddress& address, int backlog = 64);
/// Creates a server socket, binds it /// Creates a server socket using the default server SSL context,
/// binds it to the given address and puts it in listening
/// state.
///
/// After successful construction, the server socket
/// is ready to accept connections.
SecureServerSocket(const SocketAddress& address, int backlog, Context::Ptr pContext);
/// Creates a server socket using the given SSL context, binds it
/// to the given address and puts it in listening /// to the given address and puts it in listening
/// state. /// state.
/// ///
@@ -73,7 +90,15 @@ public:
/// is ready to accept connections. /// is ready to accept connections.
SecureServerSocket(Poco::UInt16 port, int backlog = 64); SecureServerSocket(Poco::UInt16 port, int backlog = 64);
/// Creates a server socket, binds it /// Creates a server socket using the default server SSL context,
/// binds it to the given port and puts it in listening
/// state.
///
/// After successful construction, the server socket
/// is ready to accept connections.
SecureServerSocket(Poco::UInt16 port, int backlog, Context::Ptr pContext);
/// Creates a server socket using the given SSL context, binds it
/// to the given port and puts it in listening /// to the given port and puts it in listening
/// state. /// state.
/// ///
@@ -97,7 +122,7 @@ public:
/// If the queue is empty, waits until a connection /// If the queue is empty, waits until a connection
/// request completes. /// request completes.
/// ///
/// Returns a new SSL TCP socket for the connection /// Returns a new SSL socket for the connection
/// with the client. /// with the client.
/// ///
/// The client socket's address is returned in clientAddr. /// The client socket's address is returned in clientAddr.
@@ -109,8 +134,11 @@ public:
/// If the queue is empty, waits until a connection /// If the queue is empty, waits until a connection
/// request completes. /// request completes.
/// ///
/// Returns a new TCP socket for the connection /// Returns a new SSL socket for the connection
/// with the client. /// with the client.
Context::Ptr context() const;
/// Returns the SSL context used by this socket.
}; };

View File

@@ -1,7 +1,7 @@
// //
// SecureServerSocketImpl.h // SecureServerSocketImpl.h
// //
// $Id: //poco/svn/NetSSL_OpenSSL/include/Poco/Net/SecureServerSocketImpl.h#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/include/Poco/Net/SecureServerSocketImpl.h#7 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLSockets // Package: SSLSockets
@@ -9,7 +9,7 @@
// //
// Definition of the SecureServerSocketImpl class. // Definition of the SecureServerSocketImpl class.
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -43,6 +43,7 @@
#include "Poco/Net/NetSSL.h" #include "Poco/Net/NetSSL.h"
#include "Poco/Net/SecureSocketImpl.h" #include "Poco/Net/SecureSocketImpl.h"
#include "Poco/Net/ServerSocketImpl.h" #include "Poco/Net/ServerSocketImpl.h"
#include "Poco/Net/Context.h"
namespace Poco { namespace Poco {
@@ -53,8 +54,9 @@ class NetSSL_API SecureServerSocketImpl: public ServerSocketImpl
/// The SocketImpl class for SecureServerSocket. /// The SocketImpl class for SecureServerSocket.
{ {
public: public:
SecureServerSocketImpl(); SecureServerSocketImpl(Context::Ptr pContext);
/// Creates the SecureServerSocketImpl. /// Creates the SecureServerSocketImpl using the
/// given SSL context object.
SocketImpl* acceptConnection(SocketAddress& clientAddr); SocketImpl* acceptConnection(SocketAddress& clientAddr);
/// Get the next completed connection from the /// Get the next completed connection from the
@@ -69,21 +71,19 @@ public:
/// The client socket's address is returned in clientAddr. /// The client socket's address is returned in clientAddr.
void connect(const SocketAddress& address); void connect(const SocketAddress& address);
/// Initializes the socket and establishes a connection to /// Not supported by this kind of socket.
/// the TCP server at the given address.
/// ///
/// Can also be used for UDP sockets. In this case, no /// Throws a Poco::InvalidAccessException.
/// connection is established. Instead, incoming and outgoing
/// packets are restricted to the specified address.
void connect(const SocketAddress& address, const Poco::Timespan& timeout); void connect(const SocketAddress& address, const Poco::Timespan& timeout);
/// Initializes the socket, sets the socket timeout and /// Not supported by this kind of socket.
/// establishes a connection to the TCP server at the given address. ///
/// Throws a Poco::InvalidAccessException.
void connectNB(const SocketAddress& address); void connectNB(const SocketAddress& address);
/// Initializes the socket and establishes a connection to /// Not supported by this kind of socket.
/// the TCP server at the given address. Prior to opening the ///
/// connection the socket is set to nonblocking mode. /// Throws a Poco::InvalidAccessException.
void bind(const SocketAddress& address, bool reuseAddress = false); void bind(const SocketAddress& address, bool reuseAddress = false);
/// Bind a local address to the socket. /// Bind a local address to the socket.
@@ -109,40 +109,32 @@ public:
/// Close the socket. /// Close the socket.
int sendBytes(const void* buffer, int length, int flags = 0); int sendBytes(const void* buffer, int length, int flags = 0);
/// Sends the contents of the given buffer through /// Not supported by this kind of socket.
/// the socket. Any specified flags are ignored.
/// ///
/// Returns the number of bytes sent, which may be /// Throws a Poco::InvalidAccessException.
/// less than the number of bytes specified.
int receiveBytes(void* buffer, int length, int flags = 0); int receiveBytes(void* buffer, int length, int flags = 0);
/// Receives data from the socket and stores it /// Not supported by this kind of socket.
/// in buffer. Up to length bytes are received.
/// ///
/// Returns the number of bytes received. /// Throws a Poco::InvalidAccessException.
int sendTo(const void* buffer, int length, const SocketAddress& address, int flags = 0); int sendTo(const void* buffer, int length, const SocketAddress& address, int flags = 0);
/// Sends the contents of the given buffer through /// Not supported by this kind of socket.
/// the socket to the given address.
/// ///
/// Returns the number of bytes sent, which may be /// Throws a Poco::InvalidAccessException.
/// less than the number of bytes specified.
int receiveFrom(void* buffer, int length, SocketAddress& address, int flags = 0); int receiveFrom(void* buffer, int length, SocketAddress& address, int flags = 0);
/// Receives data from the socket and stores it /// Not supported by this kind of socket.
/// in buffer. Up to length bytes are received.
/// Stores the address of the sender in address.
/// ///
/// Returns the number of bytes received. /// Throws a Poco::InvalidAccessException.
void sendUrgent(unsigned char data); void sendUrgent(unsigned char data);
/// Sends one byte of urgent data through /// Not supported by this kind of socket.
/// the socket.
/// ///
/// The data is sent with the MSG_OOB flag. /// Throws a Poco::InvalidAccessException.
///
/// The preferred way for a socket to receive urgent data Context::Ptr context() const;
/// is by enabling the SO_OOBINLINE option. /// Returns the SSL context used by this socket.
protected: protected:
~SecureServerSocketImpl(); ~SecureServerSocketImpl();
@@ -153,10 +145,19 @@ private:
SecureServerSocketImpl& operator = (const SecureServerSocketImpl&); SecureServerSocketImpl& operator = (const SecureServerSocketImpl&);
private: private:
SecureSocketImpl _socket; SecureSocketImpl _impl;
}; };
//
// inlines
//
inline Context::Ptr SecureServerSocketImpl::context() const
{
return _impl.context();
}
} } // namespace Poco::Net } } // namespace Poco::Net

View File

@@ -1,7 +1,7 @@
// //
// SecureSocketImpl.h // SecureSocketImpl.h
// //
// $Id: //poco/1.3/NetSSL_OpenSSL/include/Poco/Net/SecureSocketImpl.h#2 $ // $Id: //poco/Main/NetSSL_OpenSSL/include/Poco/Net/SecureSocketImpl.h#8 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLSockets // Package: SSLSockets
@@ -9,7 +9,7 @@
// //
// Definition of the SecureSocketImpl class. // Definition of the SecureSocketImpl class.
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -42,7 +42,8 @@
#include "Poco/Net/NetSSL.h" #include "Poco/Net/NetSSL.h"
#include "Poco/Net/SocketImpl.h" #include "Poco/Net/SocketImpl.h"
#include "Poco/Net/SSLManager.h" #include "Poco/Net/Context.h"
#include "Poco/Net/X509Certificate.h"
#include <openssl/bio.h> #include <openssl/bio.h>
#include <openssl/ssl.h> #include <openssl/ssl.h>
@@ -58,11 +59,9 @@ class NetSSL_API SecureSocketImpl
/// The SocketImpl for SecureStreamSocket. /// The SocketImpl for SecureStreamSocket.
{ {
public: public:
SecureSocketImpl(); SecureSocketImpl(Poco::AutoPtr<SocketImpl> pSocketImpl, Context::Ptr pContext);
/// Creates the SecureSocketImpl. /// Creates the SecureSocketImpl using an already
/// connected stream socket.
SecureSocketImpl(SSL* _pSSL);
/// Creates the SecureSocketImpl.
virtual ~SecureSocketImpl(); virtual ~SecureSocketImpl();
/// Destroys the SecureSocketImpl. /// Destroys the SecureSocketImpl.
@@ -74,33 +73,36 @@ public:
/// If the queue is empty, waits until a connection /// If the queue is empty, waits until a connection
/// request completes. /// request completes.
/// ///
/// Returns a new TCP socket for the connection /// Returns a new SSL socket for the connection
/// with the client. /// with the client.
/// ///
/// The client socket's address is returned in clientAddr. /// The client socket's address is returned in clientAddr.
void connect(const SocketAddress& address); void acceptSSL();
/// Initializes the socket and establishes a connection to /// Performs a server-side SSL handshake and certificate verification.
void connect(const SocketAddress& address, const std::string& hostName);
/// Initializes the socket and establishes a secure connection to
/// the TCP server at the given address. /// the TCP server at the given address.
///
/// Can also be used for UDP sockets. In this case, no
/// connection is established. Instead, incoming and outgoing
/// packets are restricted to the specified address.
void connect(const SocketAddress& address, const Poco::Timespan& timeout); void connect(const SocketAddress& address, const std::string& hostName, const Poco::Timespan& timeout);
/// Initializes the socket, sets the socket timeout and /// Initializes the socket, sets the socket timeout and
/// establishes a connection to the TCP server at the given address. /// establishes a secure connection to the TCP server at the given address.
void connectNB(const SocketAddress& address); void connectNB(const SocketAddress& address, const std::string& hostName);
/// Initializes the socket and establishes a connection to /// Initializes the socket and establishes a secure connection to
/// the TCP server at the given address. Prior to opening the /// the TCP server at the given address. Prior to opening the
/// connection the socket is set to nonblocking mode. /// connection the socket is set to nonblocking mode.
void connectSSL(const std::string& hostName);
/// Performs a client-side SSL handshake and establishes a secure
/// connection over an already existing TCP connection.
void bind(const SocketAddress& address, bool reuseAddress = false); void bind(const SocketAddress& address, bool reuseAddress = false);
/// Bind a local address to the socket. /// Bind a local address to the socket.
/// ///
/// This is usually only done when establishing a server /// This is usually only done when establishing a server
/// socket. TCP clients should not bind a socket to a /// socket. SSL clients should not bind a socket to a
/// specific address. /// specific address.
/// ///
/// If reuseAddress is true, sets the SO_REUSEADDR /// If reuseAddress is true, sets the SO_REUSEADDR
@@ -116,6 +118,11 @@ public:
/// number of connections that can be queued /// number of connections that can be queued
/// for this socket. /// for this socket.
void shutdown();
/// Shuts down the connection by attempting
/// an orderly SSL shutdown, then actually
/// shutting down the TCP connection.
void close(); void close();
/// Close the socket. /// Close the socket.
@@ -132,75 +139,33 @@ public:
/// ///
/// Returns the number of bytes received. /// Returns the number of bytes received.
int sendTo(const void* buffer, int length, const SocketAddress& address, int flags = 0);
/// Sends the contents of the given buffer through
/// the socket to the given address.
///
/// Returns the number of bytes sent, which may be
/// less than the number of bytes specified.
int receiveFrom(void* buffer, int length, SocketAddress& address, int flags = 0);
/// Receives data from the socket and stores it
/// in buffer. Up to length bytes are received.
/// Stores the address of the sender in address.
///
/// Returns the number of bytes received.
void sendUrgent(unsigned char data);
/// Sends one byte of urgent data through
/// the socket.
///
/// The data is sent with the MSG_OOB flag.
///
/// The preferred way for a socket to receive urgent data
/// is by enabling the SO_OOBINLINE option.
poco_socket_t sockfd(); poco_socket_t sockfd();
// Returns the socket. /// Returns the underlying socket descriptor.
void setTunnelEndPoint(const std::string& endHost, Poco::UInt16 endPort); X509* peerCertificate() const;
/// Due to the fact that SSLConnections that run over proxies require /// Returns the peer's certificate.
/// a different connect phase (ie send an unencrypted HTTP CONNECT before
/// establishing, we must inform the socket that is only used as a proxy Context::Ptr context() const;
/// that works as a tunnel to the given endPoint. /// Returns the SSL context used for this socket.
/// Only call this method on disconnected sockets.
static long postConnectionCheck(SSLManager::ContextPtr pContext, X509* pCert, const std::string& hostName);
protected: protected:
void setSockfd(poco_socket_t sock); long verifyCertificate(const std::string& hostName);
/// Set a socket description iff no socket is already set.
void invalidate();
/// Invalidate the current socket. Must only be called on closed sockets.
static long postConnectionCheck(bool onServer, SSL* pSSL, const std::string& host);
/// PostConnectionCheck to verify that a peer really presented a valid certificate. /// PostConnectionCheck to verify that a peer really presented a valid certificate.
/// if onserver is false, used by clients to verify that a server is really the one it claims.
/// if onserver is true, used by the server to verify that a client is really the one it claims. static bool isLocalHost(const std::string& hostName);
/// Returns true iff the given host name is the local host
/// (either "localhost" or "127.0.0.1").
int handleError(int rc);
/// Handles an SSL error by throwing an appropriate exception.
void connectSSL(const SocketAddress& address); private:
/// Creates and connects an SSL connection. Set _pSSL on success or exception otherwise.
void establishTunnel();
/// Creates a socket to the proxy and sends CONNECT.
static bool containsWildcards(const std::string& commonName);
/// Checks if the commonName of a certificate contains wildcards
static bool matchByAlias(const std::string& alias, const HostEntry& heData);
/// Checks if the alias is contained in heData
private:
SecureSocketImpl(const SecureSocketImpl&); SecureSocketImpl(const SecureSocketImpl&);
SecureSocketImpl& operator = (const SecureSocketImpl&); SecureSocketImpl& operator = (const SecureSocketImpl&);
private:
BIO* _pBIO;
SSL* _pSSL; SSL* _pSSL;
SocketImpl _socket; Poco::AutoPtr<SocketImpl> _pSocket;
std::string _endHost; Context::Ptr _pContext;
Poco::UInt16 _endPort;
}; };
@@ -209,28 +174,13 @@ private:
// //
inline poco_socket_t SecureSocketImpl::sockfd() inline poco_socket_t SecureSocketImpl::sockfd()
{ {
return _socket.sockfd(); return _pSocket->sockfd();
} }
inline void SecureSocketImpl::setSockfd(poco_socket_t sock) inline Context::Ptr SecureSocketImpl::context() const
{ {
_socket.setSockfd(sock); return _pContext;
}
inline void SecureSocketImpl::invalidate()
{
_socket.invalidate();
}
inline void SecureSocketImpl::setTunnelEndPoint(const std::string& endHost, Poco::UInt16 endPort)
{
poco_assert (endPort != 0 && !endHost.empty());
_endHost = endHost;
_endPort = endPort;
} }

View File

@@ -1,7 +1,7 @@
// //
// SecureStreamSocket.h // SecureStreamSocket.h
// //
// $Id: //poco/svn/NetSSL_OpenSSL/include/Poco/Net/SecureStreamSocket.h#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/include/Poco/Net/SecureStreamSocket.h#7 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLSockets // Package: SSLSockets
@@ -9,7 +9,7 @@
// //
// Definition of the SecureStreamSocket class. // Definition of the SecureStreamSocket class.
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -42,6 +42,8 @@
#include "Poco/Net/NetSSL.h" #include "Poco/Net/NetSSL.h"
#include "Poco/Net/StreamSocket.h" #include "Poco/Net/StreamSocket.h"
#include "Poco/Net/Context.h"
#include "Poco/Net/X509Certificate.h"
namespace Poco { namespace Poco {
@@ -50,22 +52,72 @@ namespace Net {
class NetSSL_API SecureStreamSocket: public StreamSocket class NetSSL_API SecureStreamSocket: public StreamSocket
/// A subclass of StreamSocket for secure SSL sockets. /// A subclass of StreamSocket for secure SSL sockets.
///
/// A few notes about nonblocking IO:
/// sendBytes() and receiveBytes() can return a
/// negative value when using a nonblocking socket, which means
/// a SSL handshake is currently in progress and more data
/// needs to be read or written for the handshake to continue.
/// If sendBytes() or receiveBytes() return ERR_SSL_WANT_WRITE,
/// sendBytes() must be called as soon as possible (usually, after
/// select() indicates that data can be written). Likewise, if
/// ERR_SSL_WANT_READ is returned, receiveBytes() must be called
/// as soon as data is available for reading (indicated by select()).
///
/// The SSL handshake is delayed until the first sendBytes() or
/// receiveBytes() operation is performed on the socket. No automatic
/// post connection check (checking the peer certificate for a valid
/// hostname) is performed when using nonblocking I/O.
{ {
public: public:
enum
{
ERR_SSL_WANT_READ = -1,
ERR_SSL_WANT_WRITE = -2
};
SecureStreamSocket(); SecureStreamSocket();
/// Creates an unconnected stream socket. /// Creates an unconnected secure stream socket
/// using the default client SSL context.
/// ///
/// Before sending or receiving data, the socket /// Before sending or receiving data, the socket
/// must be connected with a call to connect(). /// must be connected with a call to connect().
SecureStreamSocket(const SocketAddress& address); explicit SecureStreamSocket(Context::Ptr pContext);
/// Creates a stream socket and connects it to /// Creates an unconnected secure stream socket
/// using the given SSL context.
///
/// Before sending or receiving data, the socket
/// must be connected with a call to connect().
explicit SecureStreamSocket(const SocketAddress& address);
/// Creates a secure stream socket using the default
/// client SSL context and connects it to
/// the socket specified by address. /// the socket specified by address.
SecureStreamSocket(const SocketAddress& address, Context::Ptr pContext);
/// Creates a secure stream socket using the given
/// client SSL context and connects it to
/// the socket specified by address.
SecureStreamSocket(const SocketAddress& address, const std::string& hostName);
/// Creates a secure stream socket using the default
/// client SSL context and connects it to
/// the socket specified by address.
///
/// The given host name is used for certificate verification.
SecureStreamSocket(const SocketAddress& address, const std::string& hostName, Context::Ptr pContext);
/// Creates a secure stream socket using the given
/// client SSL context and connects it to
/// the socket specified by address.
///
/// The given host name is used for certificate verification.
SecureStreamSocket(const Socket& socket); SecureStreamSocket(const Socket& socket);
/// Creates the StreamSocket with the SocketImpl /// Creates the SecureStreamSocket with the SocketImpl
/// from another socket. The SocketImpl must be /// from another socket. The SocketImpl must be
/// a StreamSocketImpl, otherwise an InvalidArgumentException /// a SecureStreamSocketImpl, otherwise an InvalidArgumentException
/// will be thrown. /// will be thrown.
virtual ~SecureStreamSocket(); virtual ~SecureStreamSocket();
@@ -77,6 +129,38 @@ public:
/// Releases the socket's SocketImpl and /// Releases the socket's SocketImpl and
/// attaches the SocketImpl from the other socket and /// attaches the SocketImpl from the other socket and
/// increments the reference count of the SocketImpl. /// increments the reference count of the SocketImpl.
X509Certificate peerCertificate() const;
/// Returns the peer's X509 certificate.
void setPeerHostName(const std::string& hostName);
/// Sets the peer's host name used for certificate validation.
const std::string& getPeerHostName() const;
/// Returns the peer's host name used for certificate validation.
static SecureStreamSocket attach(const StreamSocket& streamSocket);
/// Creates a SecureStreamSocket over an existing socket
/// connection. The given StreamSocket must be connected.
/// A SSL handshake will be performed.
static SecureStreamSocket attach(const StreamSocket& streamSocket, Context::Ptr pContext);
/// Creates a SecureStreamSocket over an existing socket
/// connection. The given StreamSocket must be connected.
/// A SSL handshake will be performed.
static SecureStreamSocket attach(const StreamSocket& streamSocket, const std::string& peerHostName);
/// Creates a SecureStreamSocket over an existing socket
/// connection. The given StreamSocket must be connected.
/// A SSL handshake will be performed.
static SecureStreamSocket attach(const StreamSocket& streamSocket, const std::string& peerHostName, Context::Ptr pContext);
/// Creates a SecureStreamSocket over an existing socket
/// connection. The given StreamSocket must be connected.
/// A SSL handshake will be performed.
Context::Ptr context() const;
/// Returns the SSL context used by this socket.
protected: protected:
SecureStreamSocket(SocketImpl* pImpl); SecureStreamSocket(SocketImpl* pImpl);

View File

@@ -1,7 +1,7 @@
// //
// SecureStreamSocketImpl.h // SecureStreamSocketImpl.h
// //
// $Id: //poco/svn/NetSSL_OpenSSL/include/Poco/Net/SecureStreamSocketImpl.h#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/include/Poco/Net/SecureStreamSocketImpl.h#7 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLSockets // Package: SSLSockets
@@ -9,7 +9,7 @@
// //
// Definition of the SecureStreamSocketImpl class. // Definition of the SecureStreamSocketImpl class.
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -43,6 +43,8 @@
#include "Poco/Net/NetSSL.h" #include "Poco/Net/NetSSL.h"
#include "Poco/Net/SecureSocketImpl.h" #include "Poco/Net/SecureSocketImpl.h"
#include "Poco/Net/StreamSocketImpl.h" #include "Poco/Net/StreamSocketImpl.h"
#include "Poco/Net/Context.h"
#include "Poco/Net/X509Certificate.h"
namespace Poco { namespace Poco {
@@ -50,26 +52,22 @@ namespace Net {
class NetSSL_API SecureStreamSocketImpl: public StreamSocketImpl class NetSSL_API SecureStreamSocketImpl: public StreamSocketImpl
/// This class implements a SSL TCP socket. /// This class implements a SSL stream socket.
{ {
public: public:
SecureStreamSocketImpl(); SecureStreamSocketImpl(Context::Ptr pContext);
/// Creates the SecureStreamSocketImpl. /// Creates the SecureStreamSocketImpl.
SecureStreamSocketImpl(SSL* _pSSL); SecureStreamSocketImpl(StreamSocketImpl* pStreamSocket, Context::Ptr pContext);
/// Creates a SecureStreamSocketImpl using the given native socket. /// Creates the SecureStreamSocketImpl.
SocketImpl* acceptConnection(SocketAddress& clientAddr); SocketImpl* acceptConnection(SocketAddress& clientAddr);
/// Get the next completed connection from the /// Not supported by a SecureStreamSocket.
/// socket's completed connection queue.
/// ///
/// If the queue is empty, waits until a connection /// Throws a Poco::InvalidAccessException.
/// request completes.
/// void acceptSSL();
/// Returns a new TCP socket for the connection /// Performs a SSL server-side handshake.
/// with the client.
///
/// The client socket's address is returned in clientAddr.
void connect(const SocketAddress& address); void connect(const SocketAddress& address);
/// Initializes the socket and establishes a connection to /// Initializes the socket and establishes a connection to
@@ -87,26 +85,19 @@ public:
/// Initializes the socket and establishes a connection to /// Initializes the socket and establishes a connection to
/// the TCP server at the given address. Prior to opening the /// the TCP server at the given address. Prior to opening the
/// connection the socket is set to nonblocking mode. /// connection the socket is set to nonblocking mode.
void connectSSL();
/// Performs a SSL client-side handshake on an already connected TCP socket.
void bind(const SocketAddress& address, bool reuseAddress = false); void bind(const SocketAddress& address, bool reuseAddress = false);
/// Bind a local address to the socket. /// Not supported by a SecureStreamSocket.
/// ///
/// This is usually only done when establishing a server /// Throws a Poco::InvalidAccessException.
/// socket. TCP clients should not bind a socket to a
/// specific address.
///
/// If reuseAddress is true, sets the SO_REUSEADDR
/// socket option.
void listen(int backlog = 64); void listen(int backlog = 64);
/// Puts the socket into listening state. /// Not supported by a SecureStreamSocket.
/// ///
/// The socket becomes a passive socket that /// Throws a Poco::InvalidAccessException.
/// can accept incoming connection requests.
///
/// The backlog argument specifies the maximum
/// number of connections that can be queued
/// for this socket.
void close(); void close();
/// Close the socket. /// Close the socket.
@@ -125,45 +116,63 @@ public:
/// Returns the number of bytes received. /// Returns the number of bytes received.
int sendTo(const void* buffer, int length, const SocketAddress& address, int flags = 0); int sendTo(const void* buffer, int length, const SocketAddress& address, int flags = 0);
/// Sends the contents of the given buffer through /// Not supported by a SecureStreamSocket.
/// the socket to the given address.
/// ///
/// Returns the number of bytes sent, which may be /// Throws a Poco::InvalidAccessException.
/// less than the number of bytes specified.
int receiveFrom(void* buffer, int length, SocketAddress& address, int flags = 0); int receiveFrom(void* buffer, int length, SocketAddress& address, int flags = 0);
/// Receives data from the socket and stores it /// Not supported by a SecureStreamSocket.
/// in buffer. Up to length bytes are received.
/// Stores the address of the sender in address.
/// ///
/// Returns the number of bytes received. /// Throws a Poco::InvalidAccessException.
void sendUrgent(unsigned char data); void sendUrgent(unsigned char data);
/// Sends one byte of urgent data through /// Not supported by a SecureStreamSocket.
/// the socket.
/// ///
/// The data is sent with the MSG_OOB flag. /// Throws a Poco::InvalidAccessException.
///
/// The preferred way for a socket to receive urgent data
/// is by enabling the SO_OOBINLINE option.
void setTunnelEndPoint(const std::string& host, Poco::UInt16 port); void shutdownReceive();
/// Due to the fact that SSLConnections that run over proxies require /// Shuts down the receiving part of the socket connection.
/// a different connect phase (ie send an unencrypted HTTP CONNECT before ///
/// establishing, we must inform the socket that it is only used as a proxy /// Since SSL does not support a half shutdown, this does
/// that works as a tunnel to the given endPoint. /// nothing.
/// Only call this method on disconnected sockets.
void shutdownSend();
/// Shuts down the receiving part of the socket connection.
///
/// Since SSL does not support a half shutdown, this does
/// nothing.
void shutdown();
/// Shuts down the SSL connection.
void setPeerHostName(const std::string& hostName);
/// Sets the peer host name for certificate validation purposes.
const std::string& getPeerHostName() const;
/// Returns the peer host name.
X509Certificate peerCertificate() const;
/// Returns the peer's X509 certificate.
Context::Ptr context() const;
/// Returns the SSL context used by this socket.
protected: protected:
~SecureStreamSocketImpl(); ~SecureStreamSocketImpl();
/// Destroys the SecureStreamSocketImpl. /// Destroys the SecureStreamSocketImpl.
static int lastError();
static void error();
static void error(const std::string& arg);
static void error(int code);
static void error(int code, const std::string& arg);
private: private:
SecureStreamSocketImpl(const SecureStreamSocketImpl&); SecureStreamSocketImpl(const SecureStreamSocketImpl&);
SecureStreamSocketImpl& operator = (const SecureStreamSocketImpl&); SecureStreamSocketImpl& operator = (const SecureStreamSocketImpl&);
private: SecureSocketImpl _impl;
SecureSocketImpl _socket; std::string _peerHostName;
friend class SecureSocketImpl; friend class SecureSocketImpl;
}; };
@@ -172,9 +181,45 @@ private:
// //
// inlines // inlines
// //
inline void SecureStreamSocketImpl::setTunnelEndPoint(const std::string& host, Poco::UInt16 port) inline const std::string& SecureStreamSocketImpl::getPeerHostName() const
{ {
_socket.setTunnelEndPoint(host, port); return _peerHostName;
}
inline Context::Ptr SecureStreamSocketImpl::context() const
{
return _impl.context();
}
inline int SecureStreamSocketImpl::lastError()
{
return SocketImpl::lastError();
}
inline void SecureStreamSocketImpl::error()
{
return SocketImpl::error();
}
inline void SecureStreamSocketImpl::error(const std::string& arg)
{
return SocketImpl::error(arg);
}
inline void SecureStreamSocketImpl::error(int code)
{
return SocketImpl::error(code);
}
inline void SecureStreamSocketImpl::error(int code, const std::string& arg)
{
return SocketImpl::error(code, arg);
} }

View File

@@ -1,7 +1,7 @@
// //
// Utility.h // Utility.h
// //
// $Id: //poco/svn/NetSSL_OpenSSL/include/Poco/Net/Utility.h#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/include/Poco/Net/Utility.h#9 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
@@ -9,7 +9,7 @@
// //
// Definition of the Utility class. // Definition of the Utility class.
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -49,20 +49,22 @@ namespace Net {
class NetSSL_API Utility class NetSSL_API Utility
/// Class Utility. helper class for init & shutdown of the OpenSSL library /// This class provides various helper functions for working
/// with the OpenSSL library.
{ {
public: public:
static int HTTPS_PORT;
/// Default port value for HHTPS
static Context::VerificationMode convertVerificationMode(const std::string& verMode); static Context::VerificationMode convertVerificationMode(const std::string& verMode);
/// Non-case sensitive conversion of a string to a VerificationMode enum. /// Non-case sensitive conversion of a string to a VerificationMode enum.
/// If verMode is illegal an OptionException is thrown. /// If verMode is illegal an InvalidArgumentException is thrown.
static std::string convertCertificateError(long errCode); static std::string convertCertificateError(long errCode);
/// Converts an SSL error code into human readable form /// Converts an SSL certificate handling error code into an error message.
static std::string convertSSLError(SSL* pSSL, int errCode); static std::string getLastError();
/// Returns the last error from the error stack
static void clearErrorStack();
/// Clears the error stack
}; };

View File

@@ -1,7 +1,7 @@
// //
// VerificationErrorArgs.h // VerificationErrorArgs.h
// //
// $Id: //poco/svn/NetSSL_OpenSSL/include/Poco/Net/VerificationErrorArgs.h#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/include/Poco/Net/VerificationErrorArgs.h#7 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
@@ -9,7 +9,7 @@
// //
// Definition of the VerificationErrorArgs class. // Definition of the VerificationErrorArgs class.
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization

View File

@@ -1,7 +1,7 @@
// //
// X509Certificate.h // X509Certificate.h
// //
// $Id: //poco/1.3/NetSSL_OpenSSL/include/Poco/Net/X509Certificate.h#3 $ // $Id: //poco/Main/NetSSL_OpenSSL/include/Poco/Net/X509Certificate.h#11 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
@@ -9,7 +9,7 @@
// //
// Definition of the X509Certificate class. // Definition of the X509Certificate class.
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -42,7 +42,9 @@
#include "Poco/Net/NetSSL.h" #include "Poco/Net/NetSSL.h"
#include "Poco/Net/Context.h" #include "Poco/Net/Context.h"
#include "Poco/DateTime.h"
#include "Poco/SharedPtr.h" #include "Poco/SharedPtr.h"
#include <set>
#include <openssl/ssl.h> #include <openssl/ssl.h>
@@ -50,21 +52,34 @@ namespace Poco {
namespace Net { namespace Net {
class HostEntry;
class NetSSL_API X509Certificate class NetSSL_API X509Certificate
/// This class represents an X509 Certificate. /// This class represents a X509 Certificate.
{ {
public: public:
X509Certificate(const std::string& file); explicit X509Certificate(std::istream& istr);
/// Loads the X509Certificate from the file /// Creates the X509Certificate object by reading
/// a certificate in PEM format from a stream.
X509Certificate(X509* pCert); explicit X509Certificate(const std::string& path);
/// Creates the X509Certificate. /// Creates the X509Certificate object by reading
/// a certificate in PEM format from a file.
X509Certificate(const X509Certificate&); explicit X509Certificate(X509* pCert);
/// Creates the X509Certificate from an existing
/// OpenSSL certificate. Ownership is taken of
/// the certificate.
X509Certificate& operator=(const X509Certificate&); X509Certificate(const X509Certificate& cert);
/// Creates the certificate by copying another one.
X509Certificate& operator = (const X509Certificate& cert);
/// Assigns a certificate.
void swap(X509Certificate& cert); void swap(X509Certificate& cert);
/// Exchanges the certificate with another one.
~X509Certificate(); ~X509Certificate();
/// Destroys the X509Certificate. /// Destroys the X509Certificate.
@@ -75,21 +90,39 @@ public:
const std::string& subjectName() const; const std::string& subjectName() const;
/// Returns the certificate subject name. /// Returns the certificate subject name.
const X509* certificate() const; std::string commonName() const;
/// Returns the OpenSSL certificate. /// Returns the common name stored in the certificate.
bool verify(const std::string& hostName, Poco::SharedPtr<Context> ptr);
/// Verifies the validity of the certificate against the hostname.
private: const X509* certificate() const;
void initialize(); /// Returns the underlying OpenSSL certificate.
/// Extracts data from _pCert. Assumes _pCert != 0.
long verify(const std::string& hostName) const;
/// Verifies the validity of the certificate against the host name.
void extractNames(std::string& commonName, std::set<std::string>& domainNames) const;
/// Extracts the common name and the alias domain names from the
/// certificate.
Poco::DateTime validFrom() const;
/// Returns the date and time the certificate is valid from.
Poco::DateTime expiresOn() const;
/// Returns the date and time the certificate expires.
protected:
void init();
static bool containsWildcards(const std::string& commonName);
static bool matchByAlias(const std::string& alias, const HostEntry& heData);
private: private:
enum
{
NAME_BUFFER_SIZE = 256
};
std::string _issuerName; std::string _issuerName;
std::string _subjectName; std::string _subjectName;
X509* _pCert; X509* _pCert;
std::string _file;
}; };

View File

@@ -7,17 +7,8 @@ logging.formatters.f1.class = PatternFormatter
logging.formatters.f1.pattern = [%p] %t logging.formatters.f1.pattern = [%p] %t
logging.channels.c1.class = ConsoleChannel logging.channels.c1.class = ConsoleChannel
logging.channels.c1.formatter = f1 logging.channels.c1.formatter = f1
# HTTPSTimeServer.format = %W, %e %b %y %H:%M:%S %Z HTTPSTimeServer.format = %W, %e %b %y %H:%M:%S %Z
# HTTPSTimeServer.port = 9980 HTTPSTimeServer.port = 9980
# openSSL.client.privateKeyFile = ${application.configDir}any.pem
# openSSL.client.caConfig = ${application.configDir}rootcert.pem
# openSSL.client.verificationMode = relaxed
# openSSL.client.verificationDepth = 9
# openSSL.client.loadDefaultCAFile = false
# openSSL.client.cypherList = ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH
# openSSL.client.privateKeyPassphraseHandler.name = KeyFileHandler
# openSSL.client.privateKeyPassphraseHandler.options.password = test
# openSSL.client.invalidCertificateHandler = AcceptCertificateHandler
openSSL.server.privateKeyFile = ${application.configDir}any.pem openSSL.server.privateKeyFile = ${application.configDir}any.pem
openSSL.server.caConfig = ${application.configDir}rootcert.pem openSSL.server.caConfig = ${application.configDir}rootcert.pem
openSSL.server.verificationMode = none openSSL.server.verificationMode = none
@@ -25,5 +16,5 @@ openSSL.server.verificationDepth = 9
openSSL.server.loadDefaultCAFile = false openSSL.server.loadDefaultCAFile = false
openSSL.server.cypherList = ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH openSSL.server.cypherList = ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH
openSSL.server.privateKeyPassphraseHandler.name = KeyFileHandler openSSL.server.privateKeyPassphraseHandler.name = KeyFileHandler
openSSL.server.privateKeyPassphraseHandler.options.password = test openSSL.server.privateKeyPassphraseHandler.options.password = secret
openSSL.server.invalidCertificateHandler = AcceptCertificateHandler openSSL.server.invalidCertificateHandler = AcceptCertificateHandler

View File

@@ -1,48 +0,0 @@
-----BEGIN CERTIFICATE-----
MIICaDCCAdECCQCzfxSsk7yaLjANBgkqhkiG9w0BAQUFADBzMQswCQYDVQQGEwJB
VDESMBAGA1UECBMJQ2FyaW50aGlhMRIwEAYDVQQHEwlTdC4gSmFrb2IxDzANBgNV
BAoTBkFwcEluZjEPMA0GA1UEAxMGQXBwSW5mMRowGAYJKoZIhvcNAQkBFgthcHBA
aW5mLmNvbTAeFw0wNjAzMDExMzA3MzFaFw0wNjAzMzExMzA3MzFaMH4xCzAJBgNV
BAYTAkFUMRIwEAYDVQQIEwlDYXJpbnRoaWExETAPBgNVBAcTCFN0IEpha29iMRww
GgYDVQQKExNBcHBsaWVkIEluZm9ybWF0aWNzMQowCAYDVQQDFAEqMR4wHAYJKoZI
hvcNAQkBFg9pbmZvQGFwcGluZi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJ
AoGBAJHGyXDHyCYoWz+65ltNwwZbhwOGnxr9P1WMATuFJh0bPBZxKbZRdbTm9KhZ
OlvsEIsfgiYdsxURYIqXfEgISYLZcZY0pQwGEOmB+0NeC/+ENSfOlNSthx6zSVlc
zhJ7+dJOGwepHAiLr1fRuc5jogYLraE+lKTnqAAFfzwvti77AgMBAAEwDQYJKoZI
hvcNAQEFBQADgYEAY/ZoeY1ukkEJX7259NeoVM0oahlulWV0rlCqyaeosOiDORPT
m6X1w/5MTCf9VyaD1zukoSZ4QqNVjHFXcXidbB7Tgt3yRuZ5PC5LIFCDPv9mgPne
mUA70yfctNfza2z3ZiQ6NDkW3mZX+1tmxYIrJQIrkVeYeqf1Gh2nyZrUMcE=
-----END CERTIFICATE-----
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,E7AE93C9E49184EA
A2IqzNcWs+I5vzV+i+woDk56+yr58eU0Onw8eEvXkLjnSc58JU4327IF7yUbKWdW
Q7BYGGOkVFiZ7ANOwviDg5SUhxRDWCcW8dS6/p1vfdQ1C3qj2OwJjkpg0aDBIzJn
FzgguT3MF3ama77vxv0S3kOfmCj62MLqPGpj5pQ0/1hefRFbL8oAX8bXUN7/rmGM
Zc0QyzFZv2iQ04dY/6TNclwKPB4H0On4K+8BMs3PRkWA0clCaQaFO2+iwnk3XZfe
+MsKUEbLCpAQeYspYv1cw38dCdWq1KTP5aJk+oXgwjfX5cAaPTz74NTqTIsCcaTD
3vy7ukJYFlDR9Kyo7z8rMazYrKJslhnuRH0BhK9st9McwL957j5tZmrKyraCcmCx
dMAGcsis1va3ayYZpIpFqA4EhYrTM+6N8ZRfUap20+b5IQwHfTQDejUhL6rBwy7j
Ti5yD83/itoOMyXq2sV/XWfVD5zk/P5iv22O1EAQMhhnPB9K/I/JhuSGQJfn3cNh
ykOUYT0+vDeSeEVa+FVEP1W35G0alTbKbNs5Tb8KxJ3iDJUxokM//SvPXZy9hOVX
Y05imB04J15DaGbAHlNzunhuJi7121WV/JRXZRW9diE6hwpD8rwqi3FMuRUmy7U9
aFA5poKRAYlo9YtZ3YpFyjGKB6MfCQcB2opuSnQ/gbugV41m67uQ4CDwWLaNRkTb
GlsMBNcHnidg15Bsat5HaB7l250ukrI13Uw1MYdDUzaS3gPfw9aC4F2w0p3U+DPH
80/zePxtroR7T4/+rI136Rl+aMXDMOEGCX1TVP8rjuZzuRyUSUKC8Q==
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
MIICXTCCAcYCCQC1Vk/N8qR4AjANBgkqhkiG9w0BAQUFADBzMQswCQYDVQQGEwJB
VDESMBAGA1UECBMJQ2FyaW50aGlhMRIwEAYDVQQHEwlTdC4gSmFrb2IxDzANBgNV
BAoTBkFwcEluZjEPMA0GA1UEAxMGQXBwSW5mMRowGAYJKoZIhvcNAQkBFgthcHBA
aW5mLmNvbTAeFw0wNjAyMjcxMzI3MThaFw0wNjAzMjkxMzI3MThaMHMxCzAJBgNV
BAYTAkFUMRIwEAYDVQQIEwlDYXJpbnRoaWExEjAQBgNVBAcTCVN0LiBKYWtvYjEP
MA0GA1UEChMGQXBwSW5mMQ8wDQYDVQQDEwZBcHBJbmYxGjAYBgkqhkiG9w0BCQEW
C2FwcEBpbmYuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCsFXiPuicN
Im4oJwF8NuaFN+lgYwcZ6dAO3ILIR3kLA2PxF8HSQLfF8J8a4odZhLhctIMAKTxm
k0w8TW5qhL8QLdGzY9vzvkgdKOkan2t3sMeXJAfrM1AphTsmgntAQazGZjOj5p4W
jDnxQ+VXAylqwjHh49eSBxM3wgoscF4iLQIDAQABMA0GCSqGSIb3DQEBBQUAA4GB
AIpfLdXiKchPvFMhQS8xTtXvrw5dVL3yImUMYs4GQi8RrjGmfGB3yMAR7B/b8v4a
+ztfusgWAWiUKuSGTk4S8YB0fsFlmOv0WDr+PyZ4Lui/a8opbyzGE7rqpnF/s0GO
M7uLCNNwIN7WhmxcWV0KZU1wTppoSWPJda1yTbBzF9XP
-----END CERTIFICATE-----

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
// //
// download.cpp // download.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/samples/download/src/download.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/samples/download/src/download.cpp#8 $
// //
// This sample demonstrates the URIStreamOpener class. // This sample demonstrates the URIStreamOpener class.
// //
@@ -81,18 +81,10 @@ int main(int argc, char** argv)
} }
// Note: we must create the passphrase handler prior Context // Note: we must create the passphrase handler prior Context
SharedPtr<PrivateKeyPassphraseHandler> ptrConsole = new KeyConsoleHandler(false); // ask the user via console for the pwd
SharedPtr<InvalidCertificateHandler> ptrCert = new ConsoleCertificateHandler(false); // ask the user via console SharedPtr<InvalidCertificateHandler> ptrCert = new ConsoleCertificateHandler(false); // ask the user via console
SharedPtr<Context> ptrContext = new Context("any.pem", "rootcert.pem", false, Context::VERIFY_RELAXED, 9, false, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); Context::Ptr ptrContext = new Context(Context::CLIENT_USE, "", "", "rootcert.pem", Context::VERIFY_RELAXED, 9, false, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
SSLManager::instance().initializeClient(ptrConsole, ptrCert, ptrContext); SSLManager::instance().initializeClient(0, ptrCert, ptrContext);
// init of server part is not required, but we keep the code here as an example
/*
ptrConsole = new KeyConsoleHandler(true); // ask the user via console for the pwd
ptrCert = new ConsoleCertificateHandler(true); // ask the user via console
ptrContext = new Context("any.pem", "rootcert.pem", true, Context::VERIFY_NONE, 9, false, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
SSLManager::instance().initializeServer(ptrConsole, ptrCert, ptrContext);
*/
try try
{ {
URI uri(argv[1]); URI uri(argv[1]);

View File

@@ -1,13 +1,13 @@
// //
// AcceptCertificateHandler.cpp // AcceptCertificateHandler.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/src/AcceptCertificateHandler.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/src/AcceptCertificateHandler.cpp#11 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
// Module: AcceptCertificateHandler // Module: AcceptCertificateHandler
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -41,7 +41,7 @@ namespace Poco {
namespace Net { namespace Net {
AcceptCertificateHandler::AcceptCertificateHandler(bool server):InvalidCertificateHandler(server) AcceptCertificateHandler::AcceptCertificateHandler(bool server): InvalidCertificateHandler(server)
{ {
} }
@@ -51,4 +51,10 @@ AcceptCertificateHandler::~AcceptCertificateHandler()
} }
void AcceptCertificateHandler::onInvalidCertificate(const void*, VerificationErrorArgs& errorCert)
{
errorCert.setIgnoreError(true);
}
} } // namespace Poco::Net } } // namespace Poco::Net

View File

@@ -1,13 +1,13 @@
// //
// CertificateHandlerFactory.cpp // CertificateHandlerFactory.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/src/CertificateHandlerFactory.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/src/CertificateHandlerFactory.cpp#9 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
// Module: CertificateHandlerFactory // Module: CertificateHandlerFactory
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization

View File

@@ -1,13 +1,13 @@
// //
// CertificateHandlerFactoryMgr.cpp // CertificateHandlerFactoryMgr.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/src/CertificateHandlerFactoryMgr.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/src/CertificateHandlerFactoryMgr.cpp#10 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
// Module: CertificateHandlerFactoryMgr // Module: CertificateHandlerFactoryMgr
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization

View File

@@ -1,13 +1,13 @@
// //
// ConsoleCertificateHandler.cpp // ConsoleCertificateHandler.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/src/ConsoleCertificateHandler.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/src/ConsoleCertificateHandler.cpp#11 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
// Module: ConsoleCertificateHandler // Module: ConsoleCertificateHandler
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -42,7 +42,7 @@ namespace Poco {
namespace Net { namespace Net {
ConsoleCertificateHandler::ConsoleCertificateHandler(bool server):InvalidCertificateHandler(server) ConsoleCertificateHandler::ConsoleCertificateHandler(bool server): InvalidCertificateHandler(server)
{ {
} }
@@ -55,13 +55,14 @@ ConsoleCertificateHandler::~ConsoleCertificateHandler()
void ConsoleCertificateHandler::onInvalidCertificate(const void*, VerificationErrorArgs& errorCert) void ConsoleCertificateHandler::onInvalidCertificate(const void*, VerificationErrorArgs& errorCert)
{ {
const X509Certificate& aCert = errorCert.certificate(); const X509Certificate& aCert = errorCert.certificate();
std::cout << " Certificate:\n"; std::cout << "\n";
std::cout << "----------------\n"; std::cout << "WARNING: Certificate verification failed\n";
std::cout << " IssuerName: \t" << aCert.issuerName() << "\n"; std::cout << "----------------------------------------\n";
std::cout << " SubjectName:\t" << aCert.subjectName() << "\n\n"; std::cout << "Issuer Name: " << aCert.issuerName() << "\n";
std::cout << "Subject Name: " << aCert.subjectName() << "\n\n";
std::cout << "The certificate yielded the error: " << errorCert.errorMessage() << "\n\n"; std::cout << "The certificate yielded the error: " << errorCert.errorMessage() << "\n\n";
std::cout << "The error occurred at in the certificate chain at position " << errorCert.errorDepth() << "\n"; std::cout << "The error occurred in the certificate chain at position " << errorCert.errorDepth() << "\n";
std::cout << "Accept the certificate? (y,n)"; std::cout << "Accept the certificate (y,n)? ";
char c; char c;
std::cin >> c; std::cin >> c;
if (c == 'y' || c == 'Y') if (c == 'y' || c == 'Y')

View File

@@ -1,13 +1,13 @@
// //
// Context.cpp // Context.cpp
// //
// $Id: //poco/1.3/NetSSL_OpenSSL/src/Context.cpp#2 $ // $Id: //poco/Main/NetSSL_OpenSSL/src/Context.cpp#17 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
// Module: Context // Module: Context
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -37,6 +37,7 @@
#include "Poco/Net/Context.h" #include "Poco/Net/Context.h"
#include "Poco/Net/SSLManager.h" #include "Poco/Net/SSLManager.h"
#include "Poco/Net/SSLException.h" #include "Poco/Net/SSLException.h"
#include "Poco/Net/Utility.h"
#include "Poco/File.h" #include "Poco/File.h"
#include <openssl/bio.h> #include <openssl/bio.h>
#include <openssl/err.h> #include <openssl/err.h>
@@ -44,79 +45,82 @@
#include <openssl/x509v3.h> #include <openssl/x509v3.h>
using Poco::File;
namespace Poco { namespace Poco {
namespace Net { namespace Net {
Context::Context( Context::Context(
const std::string& privateKeyFile, Usage usage,
const std::string& caLocation, const std::string& privateKeyFile,
bool isServerContext, const std::string& certificateFile,
VerificationMode verMode, const std::string& caLocation,
int verificationDepth, VerificationMode verificationMode,
bool loadCAFromDefaultPath, int verificationDepth,
const std::string& cypherList):_pSSLContext(0), _mode(verMode), _server(isServerContext) bool loadDefaultCAs,
const std::string& cypherList):
_usage(usage),
_mode(verificationMode),
_pSSLContext(0)
{ {
_pSSLContext = SSL_CTX_new(SSLv23_method()); _pSSLContext = SSL_CTX_new(SSLv23_method());
if (!_pSSLContext) throw SSLException("Cannot create SSL_CTX object");
SSL_CTX_set_default_passwd_cb(_pSSLContext, &SSLManager::privateKeyPasswdCallback); SSL_CTX_set_default_passwd_cb(_pSSLContext, &SSLManager::privateKeyPasswdCallback);
Utility::clearErrorStack();
int errCode = 0; int errCode = 0;
if (!caLocation.empty()) if (!caLocation.empty())
{ {
File aFile(caLocation); Poco::File aFile(caLocation);
if (aFile.isDirectory()) if (aFile.isDirectory())
errCode = SSL_CTX_load_verify_locations(_pSSLContext, 0, caLocation.c_str()); errCode = SSL_CTX_load_verify_locations(_pSSLContext, 0, caLocation.c_str());
else else
errCode = SSL_CTX_load_verify_locations(_pSSLContext, caLocation.c_str(), 0); errCode = SSL_CTX_load_verify_locations(_pSSLContext, caLocation.c_str(), 0);
if (errCode != 1) if (errCode != 1)
{ {
std::string msg = Utility::getLastError();
SSL_CTX_free(_pSSLContext); SSL_CTX_free(_pSSLContext);
_pSSLContext = 0; throw SSLContextException(std::string("Cannot load CA file/directory at ") + caLocation, msg);
throw SSLContextException(std::string("Failed to load CA file/directory from ") + caLocation);
} }
} }
if (loadCAFromDefaultPath) if (loadDefaultCAs)
{ {
errCode = SSL_CTX_set_default_verify_paths(_pSSLContext); errCode = SSL_CTX_set_default_verify_paths(_pSSLContext);
if (errCode != 1) if (errCode != 1)
{ {
std::string msg = Utility::getLastError();
SSL_CTX_free(_pSSLContext); SSL_CTX_free(_pSSLContext);
_pSSLContext = 0; throw SSLContextException("Cannot load default CA certificates", msg);
throw SSLContextException(std::string("Failed to load CA file/directory from default location"));
} }
} }
if (!privateKeyFile.empty()) if (!privateKeyFile.empty())
{ {
errCode = SSL_CTX_use_certificate_chain_file(_pSSLContext, privateKeyFile.c_str());
if (errCode != 1)
{
SSL_CTX_free(_pSSLContext);
_pSSLContext = 0;
throw SSLContextException(std::string("Error loading certificate from file ") + privateKeyFile);
}
File tmp(privateKeyFile);
poco_assert (tmp.exists());
errCode = SSL_CTX_use_PrivateKey_file(_pSSLContext, privateKeyFile.c_str(), SSL_FILETYPE_PEM); errCode = SSL_CTX_use_PrivateKey_file(_pSSLContext, privateKeyFile.c_str(), SSL_FILETYPE_PEM);
if (errCode != 1) if (errCode != 1)
{ {
std::string msg = Utility::getLastError();
SSL_CTX_free(_pSSLContext); SSL_CTX_free(_pSSLContext);
_pSSLContext = 0; throw SSLContextException(std::string("Error loading private key from file ") + privateKeyFile, msg);
throw SSLContextException(std::string("Error loading private key from file ") + privateKeyFile);
} }
} }
int flags = (int)verMode;
if (verMode == VERIFY_STRICT || verMode == VERIFY_ONCE) if (!certificateFile.empty())
flags |= SSL_VERIFY_PEER; {
if (serverContext()) errCode = SSL_CTX_use_certificate_chain_file(_pSSLContext, certificateFile.c_str());
SSL_CTX_set_verify(_pSSLContext, flags, &SSLManager::verifyServerCallback); if (errCode != 1)
{
std::string errMsg = Utility::getLastError();
SSL_CTX_free(_pSSLContext);
throw SSLContextException(std::string("Error loading certificate from file ") + privateKeyFile, errMsg);
}
}
if (usage == SERVER_USE)
SSL_CTX_set_verify(_pSSLContext, verificationMode, &SSLManager::verifyServerCallback);
else else
SSL_CTX_set_verify(_pSSLContext, flags, &SSLManager::verifyClientCallback); SSL_CTX_set_verify(_pSSLContext, verificationMode, &SSLManager::verifyClientCallback);
SSL_CTX_set_verify_depth(_pSSLContext, verificationDepth); SSL_CTX_set_verify_depth(_pSSLContext, verificationDepth);
SSL_CTX_set_mode(_pSSLContext, SSL_MODE_AUTO_RETRY); SSL_CTX_set_mode(_pSSLContext, SSL_MODE_AUTO_RETRY);
} }
@@ -124,11 +128,7 @@ Context::Context(
Context::~Context() Context::~Context()
{ {
if (_pSSLContext) SSL_CTX_free(_pSSLContext);
{
SSL_CTX_free(_pSSLContext);
_pSSLContext = 0;
}
} }

View File

@@ -1,13 +1,13 @@
// //
// HTTPSClientSession.cpp // HTTPSClientSession.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/src/HTTPSClientSession.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/src/HTTPSClientSession.cpp#13 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: HTTPSClient // Package: HTTPSClient
// Module: HTTPSClientSession // Module: HTTPSClientSession
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -37,12 +37,9 @@
#include "Poco/Net/HTTPSClientSession.h" #include "Poco/Net/HTTPSClientSession.h"
#include "Poco/Net/SecureStreamSocket.h" #include "Poco/Net/SecureStreamSocket.h"
#include "Poco/Net/SecureStreamSocketImpl.h" #include "Poco/Net/SecureStreamSocketImpl.h"
#include "Poco/Net/SSLManager.h"
#include "Poco/Net/HTTPRequest.h" #include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h" #include "Poco/Net/HTTPResponse.h"
#include "Poco/Net/HTTPHeaderStream.h"
#include "Poco/Net/HTTPStream.h"
#include "Poco/Net/HTTPFixedLengthStream.h"
#include "Poco/Net/HTTPChunkedStream.h"
#include "Poco/Net/NetException.h" #include "Poco/Net/NetException.h"
#include "Poco/NumberFormatter.h" #include "Poco/NumberFormatter.h"
@@ -56,24 +53,47 @@ namespace Net {
HTTPSClientSession::HTTPSClientSession(): HTTPSClientSession::HTTPSClientSession():
HTTPClientSession(SecureStreamSocket()) HTTPClientSession(SecureStreamSocket()),
_pContext(SSLManager::instance().defaultClientContext())
{ {
setPort(Utility::HTTPS_PORT); setPort(HTTPS_PORT);
} }
HTTPSClientSession::HTTPSClientSession(const SecureStreamSocket& socket): HTTPSClientSession::HTTPSClientSession(const SecureStreamSocket& socket):
HTTPClientSession(socket) HTTPClientSession(socket),
_pContext(socket.context())
{ {
setPort(Utility::HTTPS_PORT); setPort(HTTPS_PORT);
} }
HTTPSClientSession::HTTPSClientSession(const std::string& host, Poco::UInt16 port): HTTPSClientSession::HTTPSClientSession(const std::string& host, Poco::UInt16 port):
HTTPClientSession(SecureStreamSocket()) HTTPClientSession(SecureStreamSocket()),
_pContext(SSLManager::instance().defaultClientContext())
{ {
setHost(host); setHost(host);
setPort(port); setPort(port);
SecureStreamSocket sss(socket());
sss.setPeerHostName(host);
}
HTTPSClientSession::HTTPSClientSession(Context::Ptr pContext):
HTTPClientSession(SecureStreamSocket(pContext)),
_pContext(pContext)
{
}
HTTPSClientSession::HTTPSClientSession(const std::string& host, Poco::UInt16 port, Context::Ptr pContext):
HTTPClientSession(SecureStreamSocket(pContext)),
_pContext(pContext)
{
setHost(host);
setPort(port);
SecureStreamSocket sss(socket());
sss.setPeerHostName(host);
} }
@@ -82,26 +102,45 @@ HTTPSClientSession::~HTTPSClientSession()
} }
std::string HTTPSClientSession::getHostInfo() const X509Certificate HTTPSClientSession::serverCertificate()
{ {
std::string result("https://"); SecureStreamSocket sss(socket());
result.append(getHost()); return sss.peerCertificate();
result.append(":"); }
result.append(NumberFormatter::format(getPort()));
return result;
std::string HTTPSClientSession::proxyRequestPrefix() const
{
return std::string();
} }
void HTTPSClientSession::connect(const SocketAddress& address) void HTTPSClientSession::connect(const SocketAddress& address)
{ {
if (!getProxyHost().empty()) if (getProxyHost().empty())
{ {
StreamSocket& aSock = socket(); HTTPSession::connect(address);
SecureStreamSocketImpl* pImplSock = dynamic_cast<SecureStreamSocketImpl*>(aSock.impl()); }
poco_check_ptr (pImplSock); else
pImplSock->setTunnelEndPoint(getHost(), getPort()); {
HTTPClientSession proxySession(address);
proxySession.setHost(getProxyHost());
proxySession.setPort(getProxyPort());
SocketAddress targetAddress(getHost(), getPort());
HTTPRequest proxyRequest(HTTPRequest::HTTP_CONNECT, targetAddress.toString(), HTTPMessage::HTTP_1_1);
HTTPResponse proxyResponse;
proxyRequest.set("Proxy-Connection", "keep-alive");
proxyRequest.set("Host", getHost());
proxySession.setKeepAlive(true);
proxySession.sendRequest(proxyRequest);
proxySession.receiveResponse(proxyResponse);
if (proxyResponse.getStatus() != HTTPResponse::HTTP_OK)
throw HTTPException("Cannot establish proxy connection", proxyResponse.getReason());
StreamSocket proxySocket(proxySession.detachSocket());
SecureStreamSocket secureSocket = SecureStreamSocket::attach(proxySocket, getHost(), _pContext);
attachSocket(secureSocket);
} }
HTTPSession::connect(address);
} }

View File

@@ -1,13 +1,13 @@
// //
// HTTPSSessionInstantiator.cpp // HTTPSSessionInstantiator.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/src/HTTPSSessionInstantiator.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/src/HTTPSSessionInstantiator.cpp#9 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: HTTPSClient // Package: HTTPSClient
// Module: HTTPSSessionInstantiator // Module: HTTPSSessionInstantiator
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization

View File

@@ -1,13 +1,13 @@
// //
// HTTPSStreamFactory.cpp // HTTPSStreamFactory.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/src/HTTPSStreamFactory.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/src/HTTPSStreamFactory.cpp#10 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: HTTPSClient // Package: HTTPSClient
// Module: HTTPSStreamFactory // Module: HTTPSStreamFactory
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -118,14 +118,14 @@ std::istream* HTTPSStreamFactory::open(const URI& uri)
} }
else if (res.getStatus() == HTTPResponse::HTTP_USEPROXY && !retry) else if (res.getStatus() == HTTPResponse::HTTP_USEPROXY && !retry)
{ {
//The requested resource MUST be accessed through the proxy // The requested resource MUST be accessed through the proxy
//given by the Location field. The Location field gives the // given by the Location field. The Location field gives the
//URI of the proxy. The recipient is expected to repeat this // URI of the proxy. The recipient is expected to repeat this
//single request via the proxy. 305 responses MUST only be generated by origin servers. // single request via the proxy. 305 responses MUST only be generated by origin servers.
// only use for one single request! // only use for one single request!
proxyUri.resolve(res.get("Location")); proxyUri.resolve(res.get("Location"));
delete pSession; pSession = 0; delete pSession; pSession = 0;
retry = true; //only allow useproxy once retry = true; // only allow useproxy once
} }
else else
{ {

View File

@@ -1,13 +1,13 @@
// //
// InvalidCertificateHandler.cpp // InvalidCertificateHandler.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/src/InvalidCertificateHandler.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/src/InvalidCertificateHandler.cpp#11 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
// Module: InvalidCertificateHandler // Module: InvalidCertificateHandler
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization

View File

@@ -1,13 +1,13 @@
// //
// KeyConsoleHandler.cpp // KeyConsoleHandler.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/src/KeyConsoleHandler.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/src/KeyConsoleHandler.cpp#11 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
// Module: KeyConsoleHandler // Module: KeyConsoleHandler
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -54,7 +54,7 @@ KeyConsoleHandler::~KeyConsoleHandler()
void KeyConsoleHandler::onPrivateKeyRequested(const void* pSender, std::string& privateKey) void KeyConsoleHandler::onPrivateKeyRequested(const void* pSender, std::string& privateKey)
{ {
std::cout << "Please enter the pass-phrase for the private key: "; std::cout << "Please enter the passphrase for the private key: ";
std::cin >> privateKey; std::cin >> privateKey;
} }

View File

@@ -1,13 +1,13 @@
// //
// KeyFileHandler.cpp // KeyFileHandler.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/src/KeyFileHandler.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/src/KeyFileHandler.cpp#12 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
// Module: KeyFileHandler // Module: KeyFileHandler
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -63,12 +63,12 @@ void KeyFileHandler::onPrivateKeyRequested(const void* pSender, std::string& pri
{ {
Poco::Util::LayeredConfiguration& config = Poco::Util::Application::instance().config(); Poco::Util::LayeredConfiguration& config = Poco::Util::Application::instance().config();
std::string prefix = serverSide() ? SSLManager::CFG_SERVER_PREFIX : SSLManager::CFG_CLIENT_PREFIX; std::string prefix = serverSide() ? SSLManager::CFG_SERVER_PREFIX : SSLManager::CFG_CLIENT_PREFIX;
if (!config.hasProperty(prefix+CFG_PRIV_KEY_FILE)) if (!config.hasProperty(prefix + CFG_PRIV_KEY_FILE))
{ {
throw Poco::Util::EmptyOptionException(std::string("Missing Configuration Entry: ") + prefix+CFG_PRIV_KEY_FILE); throw Poco::Util::EmptyOptionException(std::string("Missing Configuration Entry: ") + prefix + CFG_PRIV_KEY_FILE);
} }
privateKey = config.getString(prefix+CFG_PRIV_KEY_FILE); privateKey = config.getString(prefix + CFG_PRIV_KEY_FILE);
} }

View File

@@ -1,13 +1,13 @@
// //
// PrivateKeyFactory.cpp // PrivateKeyFactory.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/src/PrivateKeyFactory.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/src/PrivateKeyFactory.cpp#9 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
// Module: PrivateKeyFactory // Module: PrivateKeyFactory
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization

View File

@@ -1,13 +1,13 @@
// //
// PrivateKeyFactoryMgr.cpp // PrivateKeyFactoryMgr.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/src/PrivateKeyFactoryMgr.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/src/PrivateKeyFactoryMgr.cpp#10 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
// Module: PrivateKeyFactoryMgr // Module: PrivateKeyFactoryMgr
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization

View File

@@ -1,13 +1,13 @@
// //
// PrivateKeyPassphraseHandler.cpp // PrivateKeyPassphraseHandler.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/src/PrivateKeyPassphraseHandler.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/src/PrivateKeyPassphraseHandler.cpp#8 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
// Module: PrivateKeyPassphraseHandler // Module: PrivateKeyPassphraseHandler
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization

View File

@@ -1,13 +1,13 @@
// //
// SSLException.cpp // SSLException.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/src/SSLException.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/src/SSLException.cpp#10 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
// Module: SSLException // Module: SSLException
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -42,9 +42,10 @@ namespace Poco {
namespace Net { namespace Net {
POCO_IMPLEMENT_EXCEPTION(SSLException, NetException, "SSLException") POCO_IMPLEMENT_EXCEPTION(SSLException, NetException, "SSL Exception")
POCO_IMPLEMENT_EXCEPTION(SSLContextException, SSLException, "SSLContextException") POCO_IMPLEMENT_EXCEPTION(SSLContextException, SSLException, "SSL context exception")
POCO_IMPLEMENT_EXCEPTION(InvalidCertificateException, SSLException, "InvalidCertificateException") POCO_IMPLEMENT_EXCEPTION(InvalidCertificateException, SSLException, "Invalid certficate")
POCO_IMPLEMENT_EXCEPTION(CertificateValidationException, SSLException, "Certificate validation error")
} } // namespace Poco::Net } } // namespace Poco::Net

View File

@@ -1,13 +1,13 @@
// //
// SSLInitializer.cpp // SSLInitializer.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/src/SSLInitializer.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/src/SSLInitializer.cpp#11 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
// Module: SSLInitializer // Module: SSLInitializer
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization

View File

@@ -1,13 +1,13 @@
// //
// SSLManager.cpp // SSLManager.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/src/SSLManager.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/src/SSLManager.cpp#14 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
// Module: SSLManager // Module: SSLManager
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -39,6 +39,7 @@
#include "Poco/Net/Utility.h" #include "Poco/Net/Utility.h"
#include "Poco/Net/PrivateKeyPassphraseHandler.h" #include "Poco/Net/PrivateKeyPassphraseHandler.h"
#include "Poco/Net/SSLInitializer.h" #include "Poco/Net/SSLInitializer.h"
#include "Poco/Net/SSLException.h"
#include "Poco/SingletonHolder.h" #include "Poco/SingletonHolder.h"
#include "Poco/Delegate.h" #include "Poco/Delegate.h"
#include "Poco/Util/Application.h" #include "Poco/Util/Application.h"
@@ -51,6 +52,7 @@ namespace Net {
const std::string SSLManager::CFG_PRIV_KEY_FILE("privateKeyFile"); const std::string SSLManager::CFG_PRIV_KEY_FILE("privateKeyFile");
const std::string SSLManager::CFG_CERTIFICATE_FILE("certificateFile");
const std::string SSLManager::CFG_CA_LOCATION("caConfig"); const std::string SSLManager::CFG_CA_LOCATION("caConfig");
const std::string SSLManager::CFG_VER_MODE("verificationMode"); const std::string SSLManager::CFG_VER_MODE("verificationMode");
const Context::VerificationMode SSLManager::VAL_VER_MODE(Context::VERIFY_STRICT); const Context::VerificationMode SSLManager::VAL_VER_MODE(Context::VERIFY_STRICT);
@@ -79,12 +81,6 @@ SSLManager::~SSLManager()
PrivateKeyPassPhrase.clear(); PrivateKeyPassPhrase.clear();
ClientVerificationError.clear(); ClientVerificationError.clear();
ServerVerificationError.clear(); ServerVerificationError.clear();
_ptrServerPassPhraseHandler = 0;
_ptrServerCertificateHandler = 0;
_ptrDefaultServerContext = 0;
_ptrClientPassPhraseHandler = 0;
_ptrClientCertificateHandler = 0;
_ptrDefaultClientContext = 0;
SSLInitializer::uninitialize(); SSLInitializer::uninitialize();
} }
@@ -96,7 +92,7 @@ SSLManager& SSLManager::instance()
} }
void SSLManager::initializeServer(PrivateKeyPassphraseHandlerPtr& ptrPassPhraseHandler, InvalidCertificateHandlerPtr& ptrHandler, ContextPtr ptrContext) void SSLManager::initializeServer(PrivateKeyPassphraseHandlerPtr ptrPassPhraseHandler, InvalidCertificateHandlerPtr ptrHandler, Context::Ptr ptrContext)
{ {
_ptrServerPassPhraseHandler = ptrPassPhraseHandler; _ptrServerPassPhraseHandler = ptrPassPhraseHandler;
_ptrServerCertificateHandler = ptrHandler; _ptrServerCertificateHandler = ptrHandler;
@@ -104,7 +100,7 @@ void SSLManager::initializeServer(PrivateKeyPassphraseHandlerPtr& ptrPassPhraseH
} }
void SSLManager::initializeClient(PrivateKeyPassphraseHandlerPtr& ptrPassPhraseHandler, InvalidCertificateHandlerPtr& ptrHandler, ContextPtr ptrContext) void SSLManager::initializeClient(PrivateKeyPassphraseHandlerPtr ptrPassPhraseHandler, InvalidCertificateHandlerPtr ptrHandler, Context::Ptr ptrContext)
{ {
_ptrClientPassPhraseHandler = ptrPassPhraseHandler; _ptrClientPassPhraseHandler = ptrPassPhraseHandler;
_ptrClientCertificateHandler = ptrHandler; _ptrClientCertificateHandler = ptrHandler;
@@ -112,7 +108,7 @@ void SSLManager::initializeClient(PrivateKeyPassphraseHandlerPtr& ptrPassPhraseH
} }
SSLManager::ContextPtr SSLManager::defaultServerContext() Context::Ptr SSLManager::defaultServerContext()
{ {
if (!_ptrDefaultServerContext) if (!_ptrDefaultServerContext)
initDefaultContext(true); initDefaultContext(true);
@@ -121,7 +117,7 @@ SSLManager::ContextPtr SSLManager::defaultServerContext()
} }
SSLManager::ContextPtr SSLManager::defaultClientContext() Context::Ptr SSLManager::defaultClientContext()
{ {
if (!_ptrDefaultClientContext) if (!_ptrDefaultClientContext)
initDefaultContext(false); initDefaultContext(false);
@@ -210,34 +206,31 @@ void SSLManager::initDefaultContext(bool server)
Poco::Util::LayeredConfiguration& config = Poco::Util::Application::instance().config(); Poco::Util::LayeredConfiguration& config = Poco::Util::Application::instance().config();
std::string prefix = server ? CFG_SERVER_PREFIX : CFG_CLIENT_PREFIX; std::string prefix = server ? CFG_SERVER_PREFIX : CFG_CLIENT_PREFIX;
if (!config.hasProperty(prefix+CFG_PRIV_KEY_FILE))
{
throw Poco::Util::EmptyOptionException(std::string("Missing Configuration Entry: ") + prefix+CFG_PRIV_KEY_FILE);
}
// mandatory options // mandatory options
std::string privKeyFile = config.getString(prefix+CFG_PRIV_KEY_FILE); std::string privKeyFile = config.getString(prefix + CFG_PRIV_KEY_FILE, "");
std::string caLocation = config.getString(prefix+CFG_CA_LOCATION); std::string certFile = config.getString(prefix + CFG_CERTIFICATE_FILE, privKeyFile);
std::string caLocation = config.getString(prefix + CFG_CA_LOCATION, "");
if (certFile.empty() && privKeyFile.empty())
throw SSLException("Configuration error: no certificate file has been specified.");
// optional options for which we have defaults defined // optional options for which we have defaults defined
Context::VerificationMode verMode = VAL_VER_MODE; Context::VerificationMode verMode = VAL_VER_MODE;
if (config.hasProperty(prefix+CFG_VER_MODE)) if (config.hasProperty(prefix + CFG_VER_MODE))
{ {
// either: none, relaxed, strict, once // either: none, relaxed, strict, once
std::string mode = config.getString(prefix+CFG_VER_MODE); std::string mode = config.getString(prefix + CFG_VER_MODE);
verMode = Utility::convertVerificationMode(mode); verMode = Utility::convertVerificationMode(mode);
} }
int verDepth = config.getInt(prefix+CFG_VER_DEPTH, VAL_VER_DEPTH); int verDepth = config.getInt(prefix + CFG_VER_DEPTH, VAL_VER_DEPTH);
bool loadDefCA = config.getBool(prefix+CFG_ENABLE_DEFAULT_CA, VAL_ENABLE_DEFAULT_CA); bool loadDefCA = config.getBool(prefix + CFG_ENABLE_DEFAULT_CA, VAL_ENABLE_DEFAULT_CA);
std::string cypherList = config.getString(prefix+CFG_CYPHER_LIST, VAL_CYPHER_LIST); std::string cypherList = config.getString(prefix + CFG_CYPHER_LIST, VAL_CYPHER_LIST);
if (server) if (server)
{ _ptrDefaultServerContext = new Context(Context::SERVER_USE, privKeyFile, certFile, caLocation, verMode, verDepth, loadDefCA, cypherList);
_ptrDefaultServerContext = new Context(privKeyFile, caLocation, server, verMode, verDepth, loadDefCA, cypherList);
}
else else
{ _ptrDefaultClientContext = new Context(Context::CLIENT_USE, privKeyFile, certFile, caLocation, verMode, verDepth, loadDefCA, cypherList);
_ptrDefaultClientContext = new Context(privKeyFile, caLocation, server, verMode, verDepth, loadDefCA, cypherList);
}
} }
@@ -256,7 +249,7 @@ void SSLManager::initPassPhraseHandler(bool server)
std::string prefix = server ? CFG_SERVER_PREFIX : CFG_CLIENT_PREFIX; std::string prefix = server ? CFG_SERVER_PREFIX : CFG_CLIENT_PREFIX;
Poco::Util::LayeredConfiguration& config = Poco::Util::Application::instance().config(); Poco::Util::LayeredConfiguration& config = Poco::Util::Application::instance().config();
std::string className(config.getString(prefix+CFG_DELEGATE_HANDLER, VAL_DELEGATE_HANDLER)); std::string className(config.getString(prefix + CFG_DELEGATE_HANDLER, VAL_DELEGATE_HANDLER));
const PrivateKeyFactory* pFactory = 0; const PrivateKeyFactory* pFactory = 0;
if (privateKeyFactoryMgr().hasFactory(className)) if (privateKeyFactoryMgr().hasFactory(className))

View File

@@ -1,13 +1,13 @@
// //
// SecureServerSocket.cpp // SecureServerSocket.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/src/SecureServerSocket.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/src/SecureServerSocket.cpp#12 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLSockets // Package: SSLSockets
// Module: SecureServerSocket // Module: SecureServerSocket
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -37,6 +37,7 @@
#include "Poco/Net/SecureServerSocket.h" #include "Poco/Net/SecureServerSocket.h"
#include "Poco/Net/SecureServerSocketImpl.h" #include "Poco/Net/SecureServerSocketImpl.h"
#include "Poco/Net/SecureStreamSocket.h" #include "Poco/Net/SecureStreamSocket.h"
#include "Poco/Net/SSLManager.h"
#include "Poco/Exception.h" #include "Poco/Exception.h"
@@ -48,7 +49,13 @@ namespace Net {
SecureServerSocket::SecureServerSocket(): SecureServerSocket::SecureServerSocket():
ServerSocket(new SecureServerSocketImpl, true) ServerSocket(new SecureServerSocketImpl(SSLManager::instance().defaultServerContext()), true)
{
}
SecureServerSocket::SecureServerSocket(Context::Ptr pContext):
ServerSocket(new SecureServerSocketImpl(pContext), true)
{ {
} }
@@ -62,7 +69,15 @@ SecureServerSocket::SecureServerSocket(const Socket& socket):
SecureServerSocket::SecureServerSocket(const SocketAddress& address, int backlog): SecureServerSocket::SecureServerSocket(const SocketAddress& address, int backlog):
ServerSocket(new SecureServerSocketImpl, true) ServerSocket(new SecureServerSocketImpl(SSLManager::instance().defaultServerContext()), true)
{
impl()->bind(address, true);
impl()->listen(backlog);
}
SecureServerSocket::SecureServerSocket(const SocketAddress& address, int backlog, Context::Ptr pContext):
ServerSocket(new SecureServerSocketImpl(pContext), true)
{ {
impl()->bind(address, true); impl()->bind(address, true);
impl()->listen(backlog); impl()->listen(backlog);
@@ -70,7 +85,16 @@ SecureServerSocket::SecureServerSocket(const SocketAddress& address, int backlog
SecureServerSocket::SecureServerSocket(Poco::UInt16 port, int backlog): SecureServerSocket::SecureServerSocket(Poco::UInt16 port, int backlog):
ServerSocket(new SecureServerSocketImpl, true) ServerSocket(new SecureServerSocketImpl(SSLManager::instance().defaultServerContext()), true)
{
IPAddress wildcardAddr;
SocketAddress address(wildcardAddr, port);
impl()->bind(address, true);
impl()->listen(backlog);
}
SecureServerSocket::SecureServerSocket(Poco::UInt16 port, int backlog, Context::Ptr pContext):
ServerSocket(new SecureServerSocketImpl(pContext), true)
{ {
IPAddress wildcardAddr; IPAddress wildcardAddr;
SocketAddress address(wildcardAddr, port); SocketAddress address(wildcardAddr, port);
@@ -110,4 +134,10 @@ StreamSocket SecureServerSocket::acceptConnection()
} }
Context::Ptr SecureServerSocket::context() const
{
return static_cast<SecureServerSocketImpl*>(impl())->context();
}
} } // namespace Poco::Net } } // namespace Poco::Net

View File

@@ -1,13 +1,13 @@
// //
// SecureServerSocketImpl.cpp // SecureServerSocketImpl.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/src/SecureServerSocketImpl.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/src/SecureServerSocketImpl.cpp#9 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLSockets // Package: SSLSockets
// Module: SecureServerSocketImpl // Module: SecureServerSocketImpl
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -41,7 +41,8 @@ namespace Poco {
namespace Net { namespace Net {
SecureServerSocketImpl::SecureServerSocketImpl() SecureServerSocketImpl::SecureServerSocketImpl(Context::Ptr pContext):
_impl(new ServerSocketImpl, pContext)
{ {
} }
@@ -53,78 +54,76 @@ SecureServerSocketImpl::~SecureServerSocketImpl()
SocketImpl* SecureServerSocketImpl::acceptConnection(SocketAddress& clientAddr) SocketImpl* SecureServerSocketImpl::acceptConnection(SocketAddress& clientAddr)
{ {
return _socket.acceptConnection(clientAddr); return _impl.acceptConnection(clientAddr);
} }
void SecureServerSocketImpl::connect(const SocketAddress& address) void SecureServerSocketImpl::connect(const SocketAddress& address)
{ {
_socket.connect(address); throw Poco::InvalidAccessException("Cannot connect() a SecureServerSocket");
setSockfd(_socket.sockfd());
} }
void SecureServerSocketImpl::connect(const SocketAddress& address, const Poco::Timespan& timeout) void SecureServerSocketImpl::connect(const SocketAddress& address, const Poco::Timespan& timeout)
{ {
_socket.connect(address, timeout); throw Poco::InvalidAccessException("Cannot connect() a SecureServerSocket");
setSockfd(_socket.sockfd());
} }
void SecureServerSocketImpl::connectNB(const SocketAddress& address) void SecureServerSocketImpl::connectNB(const SocketAddress& address)
{ {
_socket.connectNB(address); throw Poco::InvalidAccessException("Cannot connect() a SecureServerSocket");
setSockfd(_socket.sockfd());
} }
void SecureServerSocketImpl::bind(const SocketAddress& address, bool reuseAddress) void SecureServerSocketImpl::bind(const SocketAddress& address, bool reuseAddress)
{ {
_socket.bind(address, reuseAddress); _impl.bind(address, reuseAddress);
reset(_impl.sockfd());
} }
void SecureServerSocketImpl::listen(int backlog) void SecureServerSocketImpl::listen(int backlog)
{ {
_socket.listen(backlog); _impl.listen(backlog);
setSockfd(_socket.sockfd()); reset(_impl.sockfd());
} }
void SecureServerSocketImpl::close() void SecureServerSocketImpl::close()
{ {
invalidate(); reset();
_socket.close(); _impl.close();
} }
int SecureServerSocketImpl::sendBytes(const void* buffer, int length, int flags) int SecureServerSocketImpl::sendBytes(const void* buffer, int length, int flags)
{ {
return _socket.sendBytes(buffer, length, flags); throw Poco::InvalidAccessException("Cannot sendBytes() on a SecureServerSocket");
} }
int SecureServerSocketImpl::receiveBytes(void* buffer, int length, int flags) int SecureServerSocketImpl::receiveBytes(void* buffer, int length, int flags)
{ {
return _socket.receiveBytes(buffer, length, flags); throw Poco::InvalidAccessException("Cannot receiveBytes() on a SecureServerSocket");
} }
int SecureServerSocketImpl::sendTo(const void* buffer, int length, const SocketAddress& address, int flags) int SecureServerSocketImpl::sendTo(const void* buffer, int length, const SocketAddress& address, int flags)
{ {
return _socket.sendTo(buffer, length, address, flags); throw Poco::InvalidAccessException("Cannot sendTo() on a SecureServerSocket");
} }
int SecureServerSocketImpl::receiveFrom(void* buffer, int length, SocketAddress& address, int flags) int SecureServerSocketImpl::receiveFrom(void* buffer, int length, SocketAddress& address, int flags)
{ {
return _socket.receiveFrom(buffer, length, address, flags); throw Poco::InvalidAccessException("Cannot receiveFrom() on a SecureServerSocket");
} }
void SecureServerSocketImpl::sendUrgent(unsigned char data) void SecureServerSocketImpl::sendUrgent(unsigned char data)
{ {
return _socket.sendUrgent(data); throw Poco::InvalidAccessException("Cannot sendUrgent() on a SecureServerSocket");
} }

View File

@@ -1,13 +1,13 @@
// //
// SecureSocketImpl.cpp // SecureSocketImpl.cpp
// //
// $Id: //poco/1.3/NetSSL_OpenSSL/src/SecureSocketImpl.cpp#6 $ // $Id: //poco/Main/NetSSL_OpenSSL/src/SecureSocketImpl.cpp#29 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLSockets // Package: SSLSockets
// Module: SecureSocketImpl // Module: SecureSocketImpl
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -36,19 +36,19 @@
#include "Poco/Net/SecureSocketImpl.h" #include "Poco/Net/SecureSocketImpl.h"
#include "Poco/Net/SSLException.h" #include "Poco/Net/SSLException.h"
#include "Poco/Net/SSLManager.h" #include "Poco/Net/Context.h"
#include "Poco/Net/X509Certificate.h"
#include "Poco/Net/Utility.h" #include "Poco/Net/Utility.h"
#include "Poco/Net/SecureStreamSocket.h"
#include "Poco/Net/SecureStreamSocketImpl.h" #include "Poco/Net/SecureStreamSocketImpl.h"
#include "Poco/Net/StreamSocketImpl.h" #include "Poco/Net/StreamSocketImpl.h"
#include "Poco/Net/StreamSocket.h"
#include "Poco/Net/NetException.h" #include "Poco/Net/NetException.h"
#include "Poco/Net/DNS.h" #include "Poco/Net/DNS.h"
#include "Poco/NumberFormatter.h" #include "Poco/NumberFormatter.h"
#include "Poco/NumberParser.h" #include "Poco/NumberParser.h"
#include "Poco/String.h"
#include "Poco/RegularExpression.h"
#include <openssl/x509v3.h> #include <openssl/x509v3.h>
#include <openssl/err.h> #include <openssl/err.h>
#include <set>
using Poco::IOException; using Poco::IOException;
@@ -62,29 +62,17 @@ using Poco::Timespan;
#define POCO_BIO_set_nbio_accept(b,n) BIO_ctrl(b,BIO_C_SET_ACCEPT,1,(void*)((n)?"a":NULL)) #define POCO_BIO_set_nbio_accept(b,n) BIO_ctrl(b,BIO_C_SET_ACCEPT,1,(void*)((n)?"a":NULL))
namespace Poco { namespace Poco {
namespace Net { namespace Net {
static void getCertNames (X509*, std::string& commonName, std::set<std::string>& DNSNames); SecureSocketImpl::SecureSocketImpl(Poco::AutoPtr<SocketImpl> pSocketImpl, Context::Ptr pContext):
_pSSL(0),
_pSocket(pSocketImpl),
SecureSocketImpl::SecureSocketImpl():_pBIO(0), _pSSL(0) _pContext(pContext)
{ {
} poco_check_ptr (_pSocket);
poco_check_ptr (_pContext);
SecureSocketImpl::SecureSocketImpl(SSL *pSSL): _pSSL(pSSL)
{
poco_check_ptr (_pSSL);
_pBIO = SSL_get_rbio(_pSSL);
poco_check_ptr (_pBIO);
int tmpSocket = 0;
BIO_get_fd(_pBIO, &tmpSocket);
setSockfd(tmpSocket);
} }
@@ -96,540 +84,305 @@ SecureSocketImpl::~SecureSocketImpl()
SocketImpl* SecureSocketImpl::acceptConnection(SocketAddress& clientAddr) SocketImpl* SecureSocketImpl::acceptConnection(SocketAddress& clientAddr)
{ {
poco_assert (sockfd() != POCO_INVALID_SOCKET); poco_assert (!_pSSL);
poco_check_ptr (_pBIO);
BIO* pClient = 0; StreamSocket ss = _pSocket->acceptConnection(clientAddr);
int rc = 0; Poco::AutoPtr<SecureStreamSocketImpl> pSecureStreamSocketImpl = new SecureStreamSocketImpl(static_cast<StreamSocketImpl*>(ss.impl()), _pContext);
pSecureStreamSocketImpl->acceptSSL();
pSecureStreamSocketImpl->duplicate();
return pSecureStreamSocketImpl;
}
do
void SecureSocketImpl::acceptSSL()
{
poco_assert (!_pSSL);
BIO* pBIO = BIO_new(BIO_s_socket());
if (!pBIO) throw SSLException("Cannot create BIO object");
BIO_set_fd(pBIO, _pSocket->sockfd(), BIO_NOCLOSE);
_pSSL = SSL_new(_pContext->sslContext());
if (!_pSSL)
{ {
rc = BIO_do_accept(_pBIO); BIO_free(pBIO);
throw SSLException("Cannot create SSL object");
} }
while (rc <= 0 && _socket.lastError() == POCO_EINTR); SSL_set_bio(_pSSL, pBIO, pBIO);
if (rc > 0) try
{ {
pClient = BIO_pop(_pBIO); if (_pSocket->getBlocking())
poco_check_ptr (pClient);
SSL* pSSL = SSL_new(SSLManager::instance().defaultServerContext()->sslContext());
if (pSSL)
{ {
SSL_set_accept_state(pSSL); int err = SSL_accept(_pSSL);
SSL_set_bio(pSSL, pClient, pClient);
int err = SSL_accept(pSSL);
if (err > 0) if (err > 0)
{ {
SecureStreamSocketImpl* pSI = new SecureStreamSocketImpl(pSSL); std::string clientName = _pSocket->peerAddress().host().toString();
clientAddr = pSI->peerAddress(); long certErr = verifyCertificate(clientName);
std::string clientName = clientAddr.host().toString(); if (certErr != X509_V_OK)
if (X509_V_OK != postConnectionCheck(true, pSSL, clientName))
{ {
delete pSI; std::string msg = Utility::convertCertificateError(certErr);
pSI = 0; throw CertificateValidationException("Unacceptable certificate from " + clientName, msg);
SSL_shutdown(pSSL);
SSL_free(pSSL);
pClient = 0;
SocketImpl::error("postConnectionCheck failed"); // will throw
} }
return pSI;
} }
else else
{ {
std::string errMsg = Utility::convertSSLError(pSSL, err); handleError(err);
SSL_shutdown(pSSL);
SSL_free(pSSL);
SocketImpl::error(std::string("failed to acceptConnection: ") + errMsg);
} }
} }
else else
{ {
BIO_free(pClient); SSL_set_accept_state(_pSSL);
} }
} }
SocketImpl::error(); // will throw catch (...)
return 0; {
SSL_shutdown(_pSSL);
SSL_free(_pSSL);
_pSSL = 0;
throw;
}
} }
void SecureSocketImpl::connect(const SocketAddress& address) void SecureSocketImpl::connect(const SocketAddress& address, const std::string& hostName)
{ {
if (sockfd() == POCO_INVALID_SOCKET) poco_assert (!_pSSL);
{
if (!_pBIO)
_pBIO = BIO_new(BIO_s_connect());
}
int rc = 0; _pSocket->connect(address);
do connectSSL(hostName);
{
BIO_set_conn_hostname(_pBIO, address.host().toString().c_str());
int tmp = address.port();
BIO_set_conn_int_port(_pBIO, &tmp);
rc = BIO_do_connect(_pBIO); // returns 1 in case of ok!
}
while (rc != 1 && _socket.lastError() == POCO_EINTR);
if (rc != 1) SocketImpl::error(address.toString());
establishTunnel();
connectSSL(address);
poco_check_ptr (_pSSL);
} }
void SecureSocketImpl::connect(const SocketAddress& address, const Poco::Timespan& timeout) void SecureSocketImpl::connect(const SocketAddress& address, const std::string& hostName, const Poco::Timespan& timeout)
{ {
poco_assert (sockfd() == POCO_INVALID_SOCKET); poco_assert (!_pSSL);
poco_assert (_pSSL == 0);
poco_assert (_pBIO == 0);
_pBIO = BIO_new(BIO_s_connect()); _pSocket->connect(address, timeout);
POCO_BIO_set_nbio_accept(_pBIO, 1); // set nonblocking connectSSL(hostName);
}
void SecureSocketImpl::connectNB(const SocketAddress& address, const std::string& hostName)
{
poco_assert (!_pSSL);
_pSocket->connectNB(address);
connectSSL(hostName);
}
void SecureSocketImpl::connectSSL(const std::string& hostName)
{
poco_assert (!_pSSL);
poco_assert (_pSocket->initialized());
BIO* pBIO = BIO_new(BIO_s_socket());
if (!pBIO) throw SSLException("Cannot create SSL BIO object");
BIO_set_fd(pBIO, _pSocket->sockfd(), BIO_NOCLOSE);
_pSSL = SSL_new(_pContext->sslContext());
if (!_pSSL)
{
BIO_free(pBIO);
throw SSLException("Cannot create SSL object");
}
SSL_set_bio(_pSSL, pBIO, pBIO);
try try
{ {
BIO_set_conn_hostname(_pBIO, address.host().toString().c_str()); if (_pSocket->getBlocking())
int tmp = address.port();
BIO_set_conn_int_port(_pBIO, &tmp);
int rc = BIO_do_connect(_pBIO); // returns 1 in case of ok!
if (rc != 1)
{ {
if (_socket.lastError() != POCO_EINPROGRESS && _socket.lastError() != POCO_EWOULDBLOCK) int ret = SSL_connect(_pSSL);
SocketImpl::error(address.toString()); handleError(ret);
if (!_socket.poll(timeout, SocketImpl::SELECT_READ | SocketImpl::SELECT_WRITE))
throw Poco::TimeoutException("connect timed out", address.toString()); long certErr = verifyCertificate(hostName);
int err = _socket.socketError(); if (certErr != X509_V_OK)
if (err != 0) SocketImpl::error(err); {
std::string msg = Utility::convertCertificateError(certErr);
throw InvalidCertificateException(msg);
}
}
else
{
SSL_set_connect_state(_pSSL);
} }
establishTunnel();
connectSSL(address);
poco_check_ptr (_pSSL);
} }
catch (Poco::Exception&) catch (...)
{ {
POCO_BIO_set_nbio_accept(_pBIO, 0); SSL_free(_pSSL);
_pSSL = 0;
throw; throw;
} }
POCO_BIO_set_nbio_accept(_pBIO, 0);
}
void SecureSocketImpl::connectNB(const SocketAddress& address)
{
if (sockfd() == POCO_INVALID_SOCKET)
{
if(!_pBIO)
_pBIO = BIO_new(BIO_s_connect());
}
POCO_BIO_set_nbio_accept(_pBIO, 1); //setnonBlocking
BIO_set_conn_hostname(_pBIO, address.host().toString().c_str());
int tmp = address.port();
BIO_set_conn_int_port(_pBIO, &tmp);
int rc = BIO_do_connect(_pBIO); // returns 1 in case of ok!
if (rc != 1)
{
if (_socket.lastError() != POCO_EINPROGRESS && _socket.lastError() != POCO_EWOULDBLOCK)
SocketImpl::error(address.toString());
}
else
{
establishTunnel();
connectSSL(address);
poco_check_ptr (_pSSL);
}
} }
void SecureSocketImpl::bind(const SocketAddress& address, bool reuseAddress) void SecureSocketImpl::bind(const SocketAddress& address, bool reuseAddress)
{ {
_socket.bind(address, reuseAddress); poco_check_ptr (_pSocket);
_pSocket->bind(address, reuseAddress);
} }
void SecureSocketImpl::listen(int backlog) void SecureSocketImpl::listen(int backlog)
{ {
_socket.listen(backlog); poco_check_ptr (_pSocket);
_pBIO = BIO_new (BIO_s_accept());
BIO_set_fd(_pBIO, (int)sockfd(), BIO_CLOSE); _pSocket->listen(backlog);
}
void SecureSocketImpl::shutdown()
{
if (_pSSL)
{
// if we can't get a clean SSL shutdown after 10
// attempts, something's probably wrong with the
// peer and we give up.
int rc;
int attempts = 0;
do
{
rc = SSL_shutdown(_pSSL);
++attempts;
}
while (rc == 0 && attempts < 10);
if (rc < 0) handleError(rc);
SSL_clear(_pSSL);
SSL_free(_pSSL);
_pSSL = 0;
}
} }
void SecureSocketImpl::close() void SecureSocketImpl::close()
{ {
if (_pSSL) shutdown();
{ _pSocket->close();
if (SSL_get_shutdown(_pSSL) & SSL_RECEIVED_SHUTDOWN)
{
SSL_shutdown(_pSSL);
}
else
{
SSL_clear(_pSSL);
}
SSL_free(_pSSL); // frees _pBIO
_pSSL = 0;
_pBIO = 0;
}
if (_pBIO)
{
BIO_free_all(_pBIO); //free all, even BIOs for pending connections
_pBIO = 0;
}
invalidate(); // the socket is already invalid, although the fd still contains a meaningful value, correct that
} }
int SecureSocketImpl::sendBytes(const void* buffer, int length, int flags) int SecureSocketImpl::sendBytes(const void* buffer, int length, int flags)
{ {
poco_assert (sockfd() != POCO_INVALID_SOCKET); poco_assert (_pSocket->initialized());
if (!_pSSL) poco_check_ptr (_pSSL);
throw SSLException("Cannot write to closed/uninitialized socket");
int rc; int rc;
do do
{ {
rc = SSL_write(_pSSL, buffer, length); rc = SSL_write(_pSSL, buffer, length);
if (rc < 0)
{
std::string errMsg = Utility::convertSSLError(_pSSL, rc);
}
} }
while (rc < 0 && _socket.lastError() == POCO_EINTR); while (rc <= 0 && _pSocket->lastError() == POCO_EINTR);
if (rc < 0) SocketImpl::error(); if (rc <= 0)
{
return handleError(rc);
}
return rc; return rc;
} }
int SecureSocketImpl::receiveBytes(void* buffer, int length, int flags) int SecureSocketImpl::receiveBytes(void* buffer, int length, int flags)
{ {
if (sockfd() == POCO_INVALID_SOCKET || !_pSSL) poco_assert (_pSocket->initialized());
throw SSLException("Cannot read from closed/uninitialized socket"); poco_check_ptr (_pSSL);
int rc; int rc;
bool renegotiating = false;
do do
{ {
rc = SSL_read(_pSSL, buffer, length); rc = SSL_read(_pSSL, buffer, length);
if (rc <= 0)
{
switch (SSL_get_error(_pSSL, rc))
{
case SSL_ERROR_ZERO_RETURN:
// connection closed
close();
break;
case SSL_ERROR_NONE:
case SSL_ERROR_WANT_WRITE: //renegotiation
case SSL_ERROR_WANT_READ: //renegotiation
renegotiating = true;
break;
default:
;
}
}
} }
while (rc < 0 && _socket.lastError() == POCO_EINTR); while (rc <= 0 && _pSocket->lastError() == POCO_EINTR);
if (rc < 0) if (rc <= 0)
{ {
if (renegotiating || _socket.lastError() == POCO_EAGAIN || _socket.lastError() == POCO_ETIMEDOUT) return handleError(rc);
throw TimeoutException();
else
SocketImpl::error("failed to read bytes");
} }
return rc; return rc;
} }
int SecureSocketImpl::sendTo(const void* buffer, int length, const SocketAddress& address, int flags) long SecureSocketImpl::verifyCertificate(const std::string& hostName)
{ {
throw NetException("sendTo not possible with SSL"); Context::VerificationMode mode = _pContext->verificationMode();
} if (mode == Context::VERIFY_NONE || isLocalHost(hostName) && mode != Context::VERIFY_STRICT)
int SecureSocketImpl::receiveFrom(void* buffer, int length, SocketAddress& address, int flags)
{
throw NetException("receiveFrom not possible with SSL");
}
void SecureSocketImpl::sendUrgent(unsigned char data)
{
// SSL doesn't support out-of-band data
sendBytes(reinterpret_cast<const void*>(&data), sizeof(data));
}
long SecureSocketImpl::postConnectionCheck(bool server, SSL* pSSL, const std::string& hostName)
{
static std::string locHost("127.0.0.1");
SSLManager& mgr = SSLManager::instance();
SSLManager::ContextPtr pContext = server? mgr.defaultServerContext(): mgr.defaultClientContext();
Context::VerificationMode mode = pContext->verificationMode();
if (hostName == locHost && mode != Context::VERIFY_STRICT)
return X509_V_OK;
X509* cert = 0;
X509_NAME* subj = 0;
if (mode == Context::VERIFY_NONE) // should we allow none on the client side?
{ {
return X509_V_OK; return X509_V_OK;
} }
cert = SSL_get_peer_certificate(pSSL); X509* pCert = SSL_get_peer_certificate(_pSSL);
return postConnectionCheck(pContext, cert, hostName); if (pCert)
{
X509Certificate cert(pCert);
return cert.verify(hostName);
}
else return X509_V_OK;
} }
long SecureSocketImpl::postConnectionCheck(SSLManager::ContextPtr pContext, X509* pCert, const std::string& hostName)
bool SecureSocketImpl::isLocalHost(const std::string& hostName)
{ {
static std::string locHost("127.0.0.1"); SocketAddress addr(hostName, 0);
return addr.host().isLoopback();
}
SSLManager& mgr = SSLManager::instance();
bool server = pContext->serverContext();
Context::VerificationMode mode = pContext->verificationMode();
if (hostName == locHost && mode != Context::VERIFY_STRICT)
return X509_V_OK;
X509* cert = pCert; X509* SecureSocketImpl::peerCertificate() const
X509_NAME* subj = 0; {
char* host = const_cast<char*>(hostName.c_str()); if (_pSSL)
return SSL_get_peer_certificate(_pSSL);
int extcount=0; else
return 0;
}
if (mode == Context::VERIFY_NONE) // should we allow none on the client side?
int SecureSocketImpl::handleError(int rc)
{
if (rc > 0) return rc;
int sslError = SSL_get_error(_pSSL, rc);
switch (sslError)
{ {
return X509_V_OK; case SSL_ERROR_ZERO_RETURN:
} return 0;
case SSL_ERROR_WANT_READ:
// note: the check is used by the client, so as long we don't set None at the client we reject return SecureStreamSocket::ERR_SSL_WANT_READ;
// cases where no certificate/incomplete info is presented by the server case SSL_ERROR_WANT_WRITE:
if ((!cert || !host) && mode != Context::VERIFY_NONE) return SecureStreamSocket::ERR_SSL_WANT_WRITE;
{ case SSL_ERROR_WANT_CONNECT:
if (cert) case SSL_ERROR_WANT_ACCEPT:
X509_free(cert); case SSL_ERROR_WANT_X509_LOOKUP:
return X509_V_ERR_APPLICATION_VERIFICATION; // these should not occur
} poco_bugcheck();
return rc;
std::string commonName; case SSL_ERROR_SYSCALL:
std::set<std::string> dnsNames; case SSL_ERROR_SSL:
getCertNames(cert, commonName, dnsNames);
bool ok = (dnsNames.find(hostName) != dnsNames.end());
char data[256];
if (!ok && (subj = X509_get_subject_name(cert)) && X509_NAME_get_text_by_NID(subj, NID_commonName, data, 256) > 0)
{
data[255] = 0;
std::string strData(data); // commonName can contain wildcards like *.appinf.com
try
{ {
// two cases: strData contains wildcards or not long lastError = ERR_get_error();
if (SecureSocketImpl::containsWildcards(strData)) if (lastError == 0)
{ {
// a compare by IPAddress is not possible with wildcards if (rc == 0)
// only allow compare by name {
const HostEntry& heData = DNS::resolve(hostName); throw SSLException("The underlying socket connection has been unexpectedly closed");
ok = SecureSocketImpl::matchByAlias(strData, heData); }
else if (rc == -1)
{
SecureStreamSocketImpl::error("The BIO reported an error");
}
} }
else else
{ {
// it depends on hostname if we compare by IP or by alias char buffer[256];
IPAddress ip; ERR_error_string_n(lastError, buffer, sizeof(buffer));
if (IPAddress::tryParse(hostName, ip)) std::string msg(buffer);
{ throw SSLException(msg);
// compare by IP
const HostEntry& heData = DNS::resolve(strData);
const HostEntry::AddressList& addr = heData.addresses();
HostEntry::AddressList::const_iterator it = addr.begin();
HostEntry::AddressList::const_iterator itEnd = addr.end();
for (; it != itEnd && !ok; ++it)
{
ok = (*it == ip);
}
}
else
{
// compare by name
const HostEntry& heData = DNS::resolve(hostName);
ok = SecureSocketImpl::matchByAlias(strData, heData);
}
} }
} }
catch(HostNotFoundException&) break;
{ default:
if (cert) break;
X509_free(cert);
return X509_V_ERR_APPLICATION_VERIFICATION;
}
} }
return rc;
if (cert)
X509_free(cert);
// we already have a verify callback registered so no need to ask twice SSL_get_verify_result(pSSL);
if (ok)
return X509_V_OK;
return X509_V_ERR_APPLICATION_VERIFICATION;
}
void SecureSocketImpl::connectSSL(const SocketAddress& address)
{
if (!_pSSL)
{
_pSSL = SSL_new(SSLManager::instance().defaultClientContext()->sslContext());
SSL_set_bio(_pSSL, _pBIO, _pBIO);
}
std::string errMsg;
int ret = SSL_connect(_pSSL);
if (ret <= 0)
{
errMsg = Utility::convertSSLError(_pSSL, ret);
throw SSLException(errMsg);
}
std::string serverName = address.host().toString();
long errCode = 0;
if (_endHost.empty())
postConnectionCheck(false, _pSSL, serverName);
else
postConnectionCheck(false, _pSSL, _endHost);
bool err = false;
if (errCode != X509_V_OK)
{
err = true;
errMsg = Utility::convertCertificateError(errCode);
}
else
{
int tmpSocket=0;
BIO_get_fd(_pBIO,&tmpSocket);
poco_assert (-1 != tmpSocket);
setSockfd(tmpSocket);
}
if (err)
{
SSL_free(_pSSL); // dels _pBIO too
_pSSL = 0;
_pBIO = 0;
invalidate();
throw InvalidCertificateException(errMsg);
}
}
void SecureSocketImpl::establishTunnel()
{
if (!_endHost.empty())
{
poco_check_ptr (_pBIO);
// send CONNECT proxyHost:proxyPort HTTP/1.0\r\n\r\n
std::string connect("CONNECT ");
connect.append(_endHost);
connect.append(":");
connect.append(Poco::NumberFormatter::format(_endPort));
connect.append(" HTTP/1.0\r\n\r\n");
int rc = BIO_write(_pBIO, (const void*) connect.c_str(), (int)(connect.length()*sizeof(char)));
if (rc != connect.length())
throw SSLException("Failed to establish connection to proxy");
// get the response
char resp[512];
rc = BIO_read(_pBIO, resp, 512*sizeof(char));
std::string response(resp);
if (response.find("200") == std::string::npos)
throw SSLException("Failed to establish connection to proxy");
}
}
bool SecureSocketImpl::containsWildcards(const std::string& commonName)
{
return (commonName.find('*') != std::string::npos || commonName.find('?') != std::string::npos);
}
bool SecureSocketImpl::matchByAlias(const std::string& alias, const HostEntry& heData)
{
// fix wildcards
std::string aliasRep = Poco::replace(alias, "*", ".*");
Poco::replaceInPlace(aliasRep, "..*", ".*");
Poco::replaceInPlace(aliasRep, "?", ".?");
Poco::replaceInPlace(aliasRep, "..?", ".?");
// compare by name
Poco::RegularExpression expr(aliasRep);
bool found = false;
const HostEntry::AliasList& aliases = heData.aliases();
HostEntry::AliasList::const_iterator it = aliases.begin();
HostEntry::AliasList::const_iterator itEnd = aliases.end();
for (; it != itEnd && !found; ++it)
{
found = expr.match(*it);
}
return found;
}
static void
getCertNames (X509 *certificate,
std::string& common_name,
std::set<std::string>& DNS_names)
{
DNS_names.clear ();
common_name.clear ();
if (certificate == 0)
{
return;
}
if (STACK_OF (GENERAL_NAME) * names = static_cast<STACK_OF (GENERAL_NAME)
*>
(X509_get_ext_d2i (certificate, NID_subject_alt_name, 0, 0)))
{
for (int i = 0; i < sk_GENERAL_NAME_num (names); ++i)
{
const GENERAL_NAME *name = sk_GENERAL_NAME_value (names, i);
if (name->type == GEN_DNS)
{
const char *data = reinterpret_cast<char *>
(ASN1_STRING_data (name->d.ia5));
size_t len = ASN1_STRING_length (name->d.ia5);
DNS_names.insert (std::string (data, len));
}
}
GENERAL_NAMES_free (names);
}
if (X509_NAME * subj = X509_get_subject_name (certificate))
{
char buffer[256];
X509_NAME_get_text_by_NID (subj, NID_commonName,
buffer, sizeof buffer);
common_name = std::string (buffer);
if (DNS_names.empty ())
{
DNS_names.insert (common_name);
}
}
} }

View File

@@ -1,13 +1,13 @@
// //
// SecureStreamSocket.cpp // SecureStreamSocket.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/src/SecureStreamSocket.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/src/SecureStreamSocket.cpp#11 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLSockets // Package: SSLSockets
// Module: SecureStreamSocket // Module: SecureStreamSocket
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -37,6 +37,7 @@
#include "Poco/Net/SecureStreamSocket.h" #include "Poco/Net/SecureStreamSocket.h"
#include "Poco/Net/SecureStreamSocketImpl.h" #include "Poco/Net/SecureStreamSocketImpl.h"
#include "Poco/Net/SocketImpl.h" #include "Poco/Net/SocketImpl.h"
#include "Poco/Net/SSLManager.h"
#include "Poco/Exception.h" #include "Poco/Exception.h"
@@ -48,18 +49,47 @@ namespace Net {
SecureStreamSocket::SecureStreamSocket(): SecureStreamSocket::SecureStreamSocket():
StreamSocket(new SecureStreamSocketImpl) StreamSocket(new SecureStreamSocketImpl(SSLManager::instance().defaultClientContext()))
{
}
SecureStreamSocket::SecureStreamSocket(Context::Ptr pContext):
StreamSocket(new SecureStreamSocketImpl(pContext))
{ {
} }
SecureStreamSocket::SecureStreamSocket(const SocketAddress& address): SecureStreamSocket::SecureStreamSocket(const SocketAddress& address):
StreamSocket(new SecureStreamSocketImpl) StreamSocket(new SecureStreamSocketImpl(SSLManager::instance().defaultClientContext()))
{ {
connect(address); connect(address);
} }
SecureStreamSocket::SecureStreamSocket(const SocketAddress& address, const std::string& hostName):
StreamSocket(new SecureStreamSocketImpl(SSLManager::instance().defaultClientContext()))
{
static_cast<SecureStreamSocketImpl*>(impl())->setPeerHostName(hostName);
connect(address);
}
SecureStreamSocket::SecureStreamSocket(const SocketAddress& address, Context::Ptr pContext):
StreamSocket(new SecureStreamSocketImpl(pContext))
{
connect(address);
}
SecureStreamSocket::SecureStreamSocket(const SocketAddress& address, const std::string& hostName, Context::Ptr pContext):
StreamSocket(new SecureStreamSocketImpl(pContext))
{
static_cast<SecureStreamSocketImpl*>(impl())->setPeerHostName(hostName);
connect(address);
}
SecureStreamSocket::SecureStreamSocket(const Socket& socket): SecureStreamSocket::SecureStreamSocket(const Socket& socket):
StreamSocket(socket) StreamSocket(socket)
{ {
@@ -91,4 +121,66 @@ SecureStreamSocket& SecureStreamSocket::operator = (const Socket& socket)
} }
X509Certificate SecureStreamSocket::peerCertificate() const
{
return static_cast<SecureStreamSocketImpl*>(impl())->peerCertificate();
}
void SecureStreamSocket::setPeerHostName(const std::string& hostName)
{
static_cast<SecureStreamSocketImpl*>(impl())->setPeerHostName(hostName);
}
const std::string& SecureStreamSocket::getPeerHostName() const
{
return static_cast<SecureStreamSocketImpl*>(impl())->getPeerHostName();
}
SecureStreamSocket SecureStreamSocket::attach(const StreamSocket& streamSocket)
{
SecureStreamSocketImpl* pImpl = new SecureStreamSocketImpl(static_cast<StreamSocketImpl*>(streamSocket.impl()), SSLManager::instance().defaultClientContext());
SecureStreamSocket result(pImpl);
pImpl->connectSSL();
return result;
}
SecureStreamSocket SecureStreamSocket::attach(const StreamSocket& streamSocket, Context::Ptr pContext)
{
SecureStreamSocketImpl* pImpl = new SecureStreamSocketImpl(static_cast<StreamSocketImpl*>(streamSocket.impl()), pContext);
SecureStreamSocket result(pImpl);
pImpl->connectSSL();
return result;
}
SecureStreamSocket SecureStreamSocket::attach(const StreamSocket& streamSocket, const std::string& peerHostName)
{
SecureStreamSocketImpl* pImpl = new SecureStreamSocketImpl(static_cast<StreamSocketImpl*>(streamSocket.impl()), SSLManager::instance().defaultClientContext());
SecureStreamSocket result(pImpl);
result.setPeerHostName(peerHostName);
pImpl->connectSSL();
return result;
}
SecureStreamSocket SecureStreamSocket::attach(const StreamSocket& streamSocket, const std::string& peerHostName, Context::Ptr pContext)
{
SecureStreamSocketImpl* pImpl = new SecureStreamSocketImpl(static_cast<StreamSocketImpl*>(streamSocket.impl()), pContext);
SecureStreamSocket result(pImpl);
result.setPeerHostName(peerHostName);
pImpl->connectSSL();
return result;
}
Context::Ptr SecureStreamSocket::context() const
{
return static_cast<SecureStreamSocketImpl*>(impl())->context();
}
} } // namespace Poco::Net } } // namespace Poco::Net

View File

@@ -1,13 +1,13 @@
// //
// SecureStreamSocketImpl.cpp // SecureStreamSocketImpl.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/src/SecureStreamSocketImpl.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/src/SecureStreamSocketImpl.cpp#9 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLSockets // Package: SSLSockets
// Module: SecureStreamSocketImpl // Module: SecureStreamSocketImpl
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -35,72 +35,92 @@
#include "Poco/Net/SecureStreamSocketImpl.h" #include "Poco/Net/SecureStreamSocketImpl.h"
#include "Poco/Net/SSLException.h"
namespace Poco { namespace Poco {
namespace Net { namespace Net {
SecureStreamSocketImpl::SecureStreamSocketImpl() SecureStreamSocketImpl::SecureStreamSocketImpl(Context::Ptr pContext):
_impl(new StreamSocketImpl, pContext)
{ {
} }
SecureStreamSocketImpl::SecureStreamSocketImpl(SSL* _pSSL): _socket(_pSSL) SecureStreamSocketImpl::SecureStreamSocketImpl(StreamSocketImpl* pStreamSocket, Context::Ptr pContext):
_impl(pStreamSocket, pContext)
{ {
setSockfd(_socket.sockfd()); pStreamSocket->duplicate();
reset(_impl.sockfd());
} }
SecureStreamSocketImpl::~SecureStreamSocketImpl() SecureStreamSocketImpl::~SecureStreamSocketImpl()
{ {
reset();
} }
SocketImpl* SecureStreamSocketImpl::acceptConnection(SocketAddress& clientAddr) SocketImpl* SecureStreamSocketImpl::acceptConnection(SocketAddress& clientAddr)
{ {
return _socket.acceptConnection(clientAddr); throw Poco::InvalidAccessException("Cannot acceptConnection() on a SecureStreamSocketImpl");
}
void SecureStreamSocketImpl::acceptSSL()
{
_impl.acceptSSL();
} }
void SecureStreamSocketImpl::connect(const SocketAddress& address) void SecureStreamSocketImpl::connect(const SocketAddress& address)
{ {
_socket.connect(address); if (_peerHostName.empty()) _peerHostName = address.host().toString();
setSockfd(_socket.sockfd()); _impl.connect(address, _peerHostName);
reset(_impl.sockfd());
} }
void SecureStreamSocketImpl::connect(const SocketAddress& address, const Poco::Timespan& timeout) void SecureStreamSocketImpl::connect(const SocketAddress& address, const Poco::Timespan& timeout)
{ {
_socket.connect(address, timeout); if (_peerHostName.empty()) _peerHostName = address.host().toString();
setSockfd(_socket.sockfd()); _impl.connect(address, _peerHostName, timeout);
reset(_impl.sockfd());
} }
void SecureStreamSocketImpl::connectNB(const SocketAddress& address) void SecureStreamSocketImpl::connectNB(const SocketAddress& address)
{ {
_socket.connectNB(address); if (_peerHostName.empty()) _peerHostName = address.host().toString();
setSockfd(_socket.sockfd()); _impl.connectNB(address, _peerHostName);
reset(_impl.sockfd());
}
void SecureStreamSocketImpl::connectSSL()
{
if (_peerHostName.empty()) _peerHostName = peerAddress().host().toString();
_impl.connectSSL(_peerHostName);
} }
void SecureStreamSocketImpl::bind(const SocketAddress& address, bool reuseAddress) void SecureStreamSocketImpl::bind(const SocketAddress& address, bool reuseAddress)
{ {
_socket.bind(address, reuseAddress); throw Poco::InvalidAccessException("Cannot bind() a SecureStreamSocketImpl");
} }
void SecureStreamSocketImpl::listen(int backlog) void SecureStreamSocketImpl::listen(int backlog)
{ {
_socket.listen(backlog); throw Poco::InvalidAccessException("Cannot listen() on a SecureStreamSocketImpl");
setSockfd(_socket.sockfd());
} }
void SecureStreamSocketImpl::close() void SecureStreamSocketImpl::close()
{ {
invalidate(); reset();
_socket.close(); _impl.close();
} }
@@ -110,7 +130,7 @@ int SecureStreamSocketImpl::sendBytes(const void* buffer, int length, int flags)
int remaining = length; int remaining = length;
while (remaining > 0) while (remaining > 0)
{ {
int n = _socket.sendBytes(p, length, flags); int n = _impl.sendBytes(p, length, flags);
p += n; p += n;
remaining -= n; remaining -= n;
} }
@@ -120,25 +140,57 @@ int SecureStreamSocketImpl::sendBytes(const void* buffer, int length, int flags)
int SecureStreamSocketImpl::receiveBytes(void* buffer, int length, int flags) int SecureStreamSocketImpl::receiveBytes(void* buffer, int length, int flags)
{ {
return _socket.receiveBytes(buffer, length, flags); return _impl.receiveBytes(buffer, length, flags);
} }
int SecureStreamSocketImpl::sendTo(const void* buffer, int length, const SocketAddress& address, int flags) int SecureStreamSocketImpl::sendTo(const void* buffer, int length, const SocketAddress& address, int flags)
{ {
return _socket.sendTo(buffer, length, address, flags); throw Poco::InvalidAccessException("Cannot sendTo() on a SecureStreamSocketImpl");
} }
int SecureStreamSocketImpl::receiveFrom(void* buffer, int length, SocketAddress& address, int flags) int SecureStreamSocketImpl::receiveFrom(void* buffer, int length, SocketAddress& address, int flags)
{ {
return _socket.receiveFrom(buffer, length, address, flags); throw Poco::InvalidAccessException("Cannot receiveFrom() on a SecureStreamSocketImpl");
} }
void SecureStreamSocketImpl::sendUrgent(unsigned char data) void SecureStreamSocketImpl::sendUrgent(unsigned char data)
{ {
return _socket.sendUrgent(data); throw Poco::InvalidAccessException("Cannot sendUrgent() on a SecureStreamSocketImpl");
}
void SecureStreamSocketImpl::shutdownReceive()
{
}
void SecureStreamSocketImpl::shutdownSend()
{
}
void SecureStreamSocketImpl::shutdown()
{
_impl.shutdown();
}
void SecureStreamSocketImpl::setPeerHostName(const std::string& peerHostName)
{
_peerHostName = peerHostName;
}
X509Certificate SecureStreamSocketImpl::peerCertificate() const
{
X509* pCert = _impl.peerCertificate();
if (pCert)
return X509Certificate(pCert);
else
throw SSLException("No certificate available yet");
} }

View File

@@ -1,13 +1,13 @@
// //
// Utility.cpp // Utility.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/src/Utility.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/src/Utility.cpp#13 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
// Module: Utility // Module: Utility
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -44,9 +44,6 @@ namespace Poco {
namespace Net { namespace Net {
int Utility::HTTPS_PORT = 443;
Context::VerificationMode Utility::convertVerificationMode(const std::string& vMode) Context::VerificationMode Utility::convertVerificationMode(const std::string& vMode)
{ {
std::string mode = Poco::toLower(vMode); std::string mode = Poco::toLower(vMode);
@@ -61,7 +58,7 @@ Context::VerificationMode Utility::convertVerificationMode(const std::string& vM
else if (mode == "once") else if (mode == "once")
verMode = Context::VERIFY_ONCE; verMode = Context::VERIFY_ONCE;
else else
throw Poco::Util::OptionException(std::string("Wrong value >") + vMode + std::string("< for a verificationMode. Can only be none, relaxed, strict or once.")); throw Poco::InvalidArgumentException("Invalid verification mode. Should be relaxed, strict or once but got", vMode);
return verMode; return verMode;
} }
@@ -74,61 +71,22 @@ std::string Utility::convertCertificateError(long errCode)
} }
std::string Utility::convertSSLError(SSL* pSSL, int errCode) std::string Utility::getLastError()
{ {
unsigned long errCode = ERR_get_error();
std::string errMsg; if (errCode != 0)
if (errCode > 0) return "no error";
int connectErr = SSL_get_error(pSSL, errCode);
long lErr = 0;
char buf[512];
switch (connectErr)
{ {
case SSL_ERROR_ZERO_RETURN: char buffer[256];
// connection closed ERR_error_string_n(errCode, buffer, sizeof(buffer));
errMsg = "connection closed by server"; return std::string(buffer);
break;
case SSL_ERROR_WANT_READ:
errMsg = "want read";
break;
case SSL_ERROR_WANT_WRITE:
errMsg = "want write";
break;
case SSL_ERROR_WANT_CONNECT:
errMsg = "want connect";
break;
case SSL_ERROR_WANT_ACCEPT:
errMsg = "want accept";
break;
case SSL_ERROR_WANT_X509_LOOKUP:
errMsg = "want lookup";
break;
case SSL_ERROR_SYSCALL:
errMsg = "syscall";
break;
case SSL_ERROR_SSL:
lErr = ERR_get_error();
if (errCode == 0)
{
errMsg = "EOF was observed";
}
else if (errCode == -1)
{
errMsg = "The underlying BIO reported an I/O error";
}
else
{
ERR_error_string_n(lErr, buf, 512);
errMsg = buf;
}
break;
default:
errMsg = "none";
} }
else return "No error";
}
return errMsg;
void Utility::clearErrorStack()
{
ERR_clear_error();
} }

View File

@@ -1,13 +1,13 @@
// //
// VerificationErrorArgs.cpp // VerificationErrorArgs.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/src/VerificationErrorArgs.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/src/VerificationErrorArgs.cpp#9 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
// Module: VerificationErrorArgs // Module: VerificationErrorArgs
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization

View File

@@ -1,13 +1,13 @@
// //
// X509Certificate.cpp // X509Certificate.cpp
// //
// $Id: //poco/1.3/NetSSL_OpenSSL/src/X509Certificate.cpp#2 $ // $Id: //poco/Main/NetSSL_OpenSSL/src/X509Certificate.cpp#13 $
// //
// Library: NetSSL_OpenSSL // Library: NetSSL_OpenSSL
// Package: SSLCore // Package: SSLCore
// Module: X509Certificate // Module: X509Certificate
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
// //
// Permission is hereby granted, free of charge, to any person or organization // Permission is hereby granted, free of charge, to any person or organization
@@ -37,69 +37,93 @@
#include "Poco/Net/X509Certificate.h" #include "Poco/Net/X509Certificate.h"
#include "Poco/Net/SSLException.h" #include "Poco/Net/SSLException.h"
#include "Poco/Net/SSLManager.h" #include "Poco/Net/SSLManager.h"
#include "Poco/Net/SecureSocketImpl.h" #include "Poco/Net/DNS.h"
#include "Poco/TemporaryFile.h"
#include "Poco/FileStream.h"
#include "Poco/StreamCopier.h"
#include "Poco/String.h"
#include "Poco/RegularExpression.h"
#include "Poco/DateTimeParser.h"
#include <openssl/pem.h> #include <openssl/pem.h>
#include <openssl/x509v3.h>
#include <openssl/err.h>
namespace Poco { namespace Poco {
namespace Net { namespace Net {
X509Certificate::X509Certificate(const std::string& file): X509Certificate::X509Certificate(std::istream& istr):
_issuerName(), _pCert(0)
_subjectName(), {
_pCert(0), // copy certificate to a temporary file so that it
_file(file) // can be read by OpenSSL.
Poco::TemporaryFile certFile;
std::string path = certFile.path();
Poco::FileOutputStream ostr(path);
Poco::StreamCopier::copyStream(istr, ostr);
ostr.close();
BIO *pBIO = BIO_new(BIO_s_file());
if (!pBIO) throw SSLException("Cannot create BIO for reading certificate file");
if (!BIO_read_filename(pBIO, path.c_str()))
{
BIO_free(pBIO);
throw Poco::OpenFileException("Cannot open certificate file for reading");
}
_pCert = PEM_read_bio_X509(pBIO, 0, 0, 0);
BIO_free(pBIO);
if (!_pCert) throw SSLException("Faild to load certificate");
init();
}
X509Certificate::X509Certificate(const std::string& path):
_pCert(0)
{ {
BIO *fp=BIO_new(BIO_s_file()); BIO *pBIO = BIO_new(BIO_s_file());
const char* pFN = file.c_str(); if (!pBIO) throw SSLException("Cannot create BIO for reading certificate file");
BIO_read_filename(fp, (void*)pFN); if (!BIO_read_filename(pBIO, path.c_str()))
if (!fp)
throw Poco::PathNotFoundException("Failed to open " + file);
try
{ {
_pCert = PEM_read_bio_X509(fp,0,0,0); BIO_free(pBIO);
throw Poco::OpenFileException("Cannot open certificate file for reading");
} }
catch(...)
{ _pCert = PEM_read_bio_X509(pBIO, 0, 0, 0);
BIO_free(fp); BIO_free(pBIO);
throw;
} if (!_pCert) throw SSLException("Faild to load certificate from " + path);
if (!_pCert)
throw SSLException("Faild to load certificate from " + file); init();
initialize();
} }
X509Certificate::X509Certificate(X509* pCert): X509Certificate::X509Certificate(X509* pCert):
_issuerName(), _pCert(pCert)
_subjectName(),
_pCert(pCert),
_file()
{ {
poco_check_ptr(_pCert); poco_check_ptr(_pCert);
initialize();
_pCert = X509_dup(_pCert);
init();
} }
X509Certificate::X509Certificate(const X509Certificate& cert): X509Certificate::X509Certificate(const X509Certificate& cert):
_issuerName(cert._issuerName), _issuerName(cert._issuerName),
_subjectName(cert._subjectName), _subjectName(cert._subjectName),
_pCert(cert._pCert), _pCert(cert._pCert)
_file(cert._file)
{ {
if (!_file.empty()) _pCert = X509_dup(_pCert);
_pCert = X509_dup(_pCert);
} }
X509Certificate& X509Certificate::operator=(const X509Certificate& cert) X509Certificate& X509Certificate::operator = (const X509Certificate& cert)
{ {
if (this != &cert) X509Certificate tmp(cert);
{ swap(tmp);
X509Certificate c(cert);
swap(c);
}
return *this; return *this;
} }
@@ -107,7 +131,6 @@ X509Certificate& X509Certificate::operator=(const X509Certificate& cert)
void X509Certificate::swap(X509Certificate& cert) void X509Certificate::swap(X509Certificate& cert)
{ {
using std::swap; using std::swap;
swap(cert._file, _file);
swap(cert._issuerName, _issuerName); swap(cert._issuerName, _issuerName);
swap(cert._subjectName, _subjectName); swap(cert._subjectName, _subjectName);
swap(cert._pCert, _pCert); swap(cert._pCert, _pCert);
@@ -116,25 +139,161 @@ void X509Certificate::swap(X509Certificate& cert)
X509Certificate::~X509Certificate() X509Certificate::~X509Certificate()
{ {
if (!_file.empty() && _pCert) X509_free(_pCert);
X509_free(_pCert);
} }
void X509Certificate::initialize() void X509Certificate::init()
{ {
char data[256]; char buffer[NAME_BUFFER_SIZE];
X509_NAME_oneline(X509_get_issuer_name(_pCert), data, 256); X509_NAME_oneline(X509_get_issuer_name(_pCert), buffer, sizeof(buffer));
_issuerName = data; _issuerName = buffer;
X509_NAME_oneline(X509_get_subject_name(_pCert), data, 256); X509_NAME_oneline(X509_get_subject_name(_pCert), buffer, sizeof(buffer));
_subjectName = data; _subjectName = buffer;
} }
bool X509Certificate::verify(const std::string& hostName, Poco::SharedPtr<Context> ptr) long X509Certificate::verify(const std::string& hostName) const
{
std::string commonName;
std::set<std::string> dnsNames;
extractNames(commonName, dnsNames);
bool ok = (dnsNames.find(hostName) != dnsNames.end());
char buffer[NAME_BUFFER_SIZE];
X509_NAME* subj = 0;
if (!ok && (subj = X509_get_subject_name(_pCert)) && X509_NAME_get_text_by_NID(subj, NID_commonName, buffer, sizeof(buffer)) > 0)
{
buffer[NAME_BUFFER_SIZE - 1] = 0;
std::string commonName(buffer); // commonName can contain wildcards like *.appinf.com
try
{
// two cases: strData contains wildcards or not
if (containsWildcards(commonName))
{
// a compare by IPAddress is not possible with wildcards
// only allow compare by name
const HostEntry& heData = DNS::resolve(hostName);
ok = matchByAlias(commonName, heData);
}
else
{
// it depends on hostName if we compare by IP or by alias
IPAddress ip;
if (IPAddress::tryParse(hostName, ip))
{
// compare by IP
const HostEntry& heData = DNS::resolve(commonName);
const HostEntry::AddressList& addr = heData.addresses();
HostEntry::AddressList::const_iterator it = addr.begin();
HostEntry::AddressList::const_iterator itEnd = addr.end();
for (; it != itEnd && !ok; ++it)
{
ok = (*it == ip);
}
}
else
{
// compare by name
const HostEntry& heData = DNS::resolve(hostName);
ok = matchByAlias(commonName, heData);
}
}
}
catch (HostNotFoundException&)
{
return X509_V_ERR_APPLICATION_VERIFICATION;
}
}
// we already have a verify callback registered so no need to ask twice SSL_get_verify_result(pSSL);
if (ok)
return X509_V_OK;
else
return X509_V_ERR_APPLICATION_VERIFICATION;
}
bool X509Certificate::containsWildcards(const std::string& commonName)
{ {
X509* pCert = X509_dup(_pCert); return (commonName.find('*') != std::string::npos || commonName.find('?') != std::string::npos);
return (X509_V_OK == SecureSocketImpl::postConnectionCheck(ptr, pCert, hostName)); }
bool X509Certificate::matchByAlias(const std::string& alias, const HostEntry& heData)
{
// fix wildcards
std::string aliasRep = Poco::replace(alias, "*", ".*");
Poco::replaceInPlace(aliasRep, "..*", ".*");
Poco::replaceInPlace(aliasRep, "?", ".?");
Poco::replaceInPlace(aliasRep, "..?", ".?");
// compare by name
Poco::RegularExpression expr(aliasRep);
bool found = false;
const HostEntry::AliasList& aliases = heData.aliases();
HostEntry::AliasList::const_iterator it = aliases.begin();
HostEntry::AliasList::const_iterator itEnd = aliases.end();
for (; it != itEnd && !found; ++it)
{
found = expr.match(*it);
}
return found;
}
std::string X509Certificate::commonName() const
{
if (X509_NAME* subj = X509_get_subject_name(_pCert))
{
char buffer[NAME_BUFFER_SIZE];
X509_NAME_get_text_by_NID(subj, NID_commonName, buffer, sizeof(buffer));
return std::string(buffer);
}
else return std::string();
}
void X509Certificate::extractNames(std::string& cmnName, std::set<std::string>& domainNames) const
{
domainNames.clear();
if (STACK_OF(GENERAL_NAME)* names = static_cast<STACK_OF(GENERAL_NAME)*>(X509_get_ext_d2i(_pCert, NID_subject_alt_name, 0, 0)))
{
for (int i = 0; i < sk_GENERAL_NAME_num(names); ++i)
{
const GENERAL_NAME* name = sk_GENERAL_NAME_value(names, i);
if (name->type == GEN_DNS)
{
const char* data = reinterpret_cast<char*>(ASN1_STRING_data(name->d.ia5));
std::size_t len = ASN1_STRING_length(name->d.ia5);
domainNames.insert(std::string(data, len));
}
}
GENERAL_NAMES_free(names);
}
cmnName = commonName();
if (!cmnName.empty() && domainNames.empty())
{
domainNames.insert(cmnName);
}
}
Poco::DateTime X509Certificate::validFrom() const
{
ASN1_TIME* certTime = X509_get_notBefore(_pCert);
std::string dateTime(reinterpret_cast<char*>(certTime->data));
int tzd;
return DateTimeParser::parse("%y%m%d%H%M%S", dateTime, tzd);
}
Poco::DateTime X509Certificate::expiresOn() const
{
ASN1_TIME* certTime = X509_get_notAfter(_pCert);
std::string dateTime(reinterpret_cast<char*>(certTime->data));
int tzd;
return DateTimeParser::parse("%y%m%d%H%M%S", dateTime, tzd);
} }

View File

@@ -10,7 +10,7 @@
<privateKeyPassphraseHandler> <privateKeyPassphraseHandler>
<name>KeyFileHandler</name> <name>KeyFileHandler</name>
<options> <options>
<password>test</password> <password>secret</password>
</options> </options>
</privateKeyPassphraseHandler> </privateKeyPassphraseHandler>
<invalidCertificateHandler> <invalidCertificateHandler>
@@ -29,7 +29,7 @@
<privateKeyPassphraseHandler> <privateKeyPassphraseHandler>
<name>KeyFileHandler</name> <name>KeyFileHandler</name>
<options> <options>
<password>test</password> <password>secret</password>
</options> </options>
</privateKeyPassphraseHandler> </privateKeyPassphraseHandler>
<invalidCertificateHandler> <invalidCertificateHandler>

View File

@@ -1,48 +1,54 @@
-----BEGIN CERTIFICATE----- -----BEGIN CERTIFICATE-----
MIICaDCCAdECCQCzfxSsk7yaLjANBgkqhkiG9w0BAQUFADBzMQswCQYDVQQGEwJB MIIEFjCCAv6gAwIBAgIBAjALBgkqhkiG9w0BAQUwgdMxEzARBgNVBAMMCmFwcGlu
VDESMBAGA1UECBMJQ2FyaW50aGlhMRIwEAYDVQQHEwlTdC4gSmFrb2IxDzANBgNV Zi5jb20xNjA0BgNVBAoMLUFwcGxpZWQgSW5mb3JtYXRpY3MgU29mdHdhcmUgRW5n
BAoTBkFwcEluZjEPMA0GA1UEAxMGQXBwSW5mMRowGAYJKoZIhvcNAQkBFgthcHBA aW5lZXJpbmcgR21iSDEUMBIGA1UECwwLRGV2ZWxvcG1lbnQxEjAQBgNVBAgMCUNh
aW5mLmNvbTAeFw0wNjAzMDExMzA3MzFaFw0wNjAzMzExMzA3MzFaMH4xCzAJBgNV cmludGhpYTELMAkGA1UEBgwCQVQxHjAcBgNVBAcMFVN0LiBKYWtvYiBpbSBSb3Nl
BAYTAkFUMRIwEAYDVQQIEwlDYXJpbnRoaWExETAPBgNVBAcTCFN0IEpha29iMRww bnRhbDEtMCsGCSqGSIb3DQEJAQweZ3VlbnRlci5vYmlsdHNjaG5pZ0BhcHBpbmYu
GgYDVQQKExNBcHBsaWVkIEluZm9ybWF0aWNzMQowCAYDVQQDFAEqMR4wHAYJKoZI Y29tMB4XDTA5MDIyMzEzNDIwMloXDTExMTEyMDEzNDIwMlowgcoxCjAIBgNVBAMM
hvcNAQkBFg9pbmZvQGFwcGluZi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJ ASoxNjA0BgNVBAoMLUFwcGxpZWQgSW5mb3JtYXRpY3MgU29mdHdhcmUgRW5naW5l
AoGBAJHGyXDHyCYoWz+65ltNwwZbhwOGnxr9P1WMATuFJh0bPBZxKbZRdbTm9KhZ ZXJpbmcgR21iSDEUMBIGA1UECwwLRGV2ZWxvcG1lbnQxEjAQBgNVBAgMCUNhcmlu
OlvsEIsfgiYdsxURYIqXfEgISYLZcZY0pQwGEOmB+0NeC/+ENSfOlNSthx6zSVlc dGhpYTELMAkGA1UEBgwCQVQxHjAcBgNVBAcMFVN0LiBKYWtvYiBpbSBSb3NlbnRh
zhJ7+dJOGwepHAiLr1fRuc5jogYLraE+lKTnqAAFfzwvti77AgMBAAEwDQYJKoZI bDEtMCsGCSqGSIb3DQEJAQweZ3VlbnRlci5vYmlsdHNjaG5pZ0BhcHBpbmYuY29t
hvcNAQEFBQADgYEAY/ZoeY1ukkEJX7259NeoVM0oahlulWV0rlCqyaeosOiDORPT MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxjGFE96wa83Kdiv0m10O
m6X1w/5MTCf9VyaD1zukoSZ4QqNVjHFXcXidbB7Tgt3yRuZ5PC5LIFCDPv9mgPne XmBmZ5xuclalVTCisLzUmAekbItMjkmI6dVw9r5gd0W5zDWrgPYUmYgtvqnxSHRK
mUA70yfctNfza2z3ZiQ6NDkW3mZX+1tmxYIrJQIrkVeYeqf1Gh2nyZrUMcE= PRAN410Yq9vqWYvQscpnXGlqUag8t+OBXJhiFnnea/btA0zGVZk6RE/7cWK8AtKH
Q/Xds3AUJ1L/1uV/e/5azyUDyptsmHbCMUwWhGBrj/KZEviHmRMN/xJLrbIBPkla
4HRB61rI8in0jziCwThJ7KiQumzWRu2IJjS+VoNWvG52dYLDvfxppuY1rlF0SG/h
JuSJQqJjZZ11V4TePHscFkGU2tnHqF4UhSjLFJWsGuxnAmZTeIRmavmIIMm3/G6C
WwIDAQABMA0GCSqGSIb3DQEBBQUAA4IBAQAc+mn/ZEaK59B/UAgx8cMlGM9UigJv
L9O46pno3YirBq9SrMzf5b6rrbJm8tkQNfldqaVNA5oVbfxnAHhCUDkX8m0x/De8
teo9nFei8kETQ25ykV+WLapOdrYxakHPtNVgDTGWNb2GY/hH3nMvtdgFvaS80ncD
tOa13tE4jopFQFY56VKq+sv4Hm5JDvr+dD/g77Cio02sUzSH96FrFIG5/kw1NihB
IJKZ4n7atQizDe4TiR/NRonmZNbsB+18yTKT8traCS30JGKQqYxXuVKPyQd7FARv
ajZxRPbcpAtvWBKXpRHXo4xIBJaPktVOG2hGovjRixXYb83hQ87t1Ozy
-----END CERTIFICATE----- -----END CERTIFICATE-----
-----BEGIN RSA PRIVATE KEY----- -----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,E7AE93C9E49184EA DEK-Info: DES-EDE3-CBC,0950752701CB74AF
A2IqzNcWs+I5vzV+i+woDk56+yr58eU0Onw8eEvXkLjnSc58JU4327IF7yUbKWdW OmaLdMcP3JDy8JMX41wNH/WvMp6gLGwmqQRob633n95YxVdii0oR8fk4GgmJeYF0
Q7BYGGOkVFiZ7ANOwviDg5SUhxRDWCcW8dS6/p1vfdQ1C3qj2OwJjkpg0aDBIzJn FrNm5g32vnVyqDZylX4as3GT822HhCA+f7mYpGZltQ47TG15tGTMUNuwIhHlouZs
FzgguT3MF3ama77vxv0S3kOfmCj62MLqPGpj5pQ0/1hefRFbL8oAX8bXUN7/rmGM ZGNclelBB3FHEZAD0Fns2hZ4jZhMDj67wD0YyGcp8so/A+fxedGdwNbJSC1Auuy4
Zc0QyzFZv2iQ04dY/6TNclwKPB4H0On4K+8BMs3PRkWA0clCaQaFO2+iwnk3XZfe 7uRsY0ZJC1LjMHXkyBEXaL1QA4CGjBlm22Dbo8eoGXcaohsZpDsM7OU7MaQnldM0
+MsKUEbLCpAQeYspYv1cw38dCdWq1KTP5aJk+oXgwjfX5cAaPTz74NTqTIsCcaTD AK8jONZ45127JoDJD41Wgfm0m7tIErsD5CbhHPaddOjQ0OerprEkplhOR+V+ano1
3vy7ukJYFlDR9Kyo7z8rMazYrKJslhnuRH0BhK9st9McwL957j5tZmrKyraCcmCx Pv4adRZOBjr00NDB43WK9x+ZHVQ5tIXxUbqYWZAfvA1PpiYego5XLUCxfy7D6Lms
dMAGcsis1va3ayYZpIpFqA4EhYrTM+6N8ZRfUap20+b5IQwHfTQDejUhL6rBwy7j hV6CAt/fYeBrQOvwLREboKLBOe9A8quP2wi7zkR3KQHty9Tm9efF3PfQSxJTlKg9
Ti5yD83/itoOMyXq2sV/XWfVD5zk/P5iv22O1EAQMhhnPB9K/I/JhuSGQJfn3cNh YJ2n/6omX1aXCjQghbnfEcl4tCmj6z2rHCSiJgEOcwDYhGRbQveYieZUH5iKMzYY
ykOUYT0+vDeSeEVa+FVEP1W35G0alTbKbNs5Tb8KxJ3iDJUxokM//SvPXZy9hOVX YytHkHPfZfzhlJ0WG0AKdA6UlrjEjF09txaZR3Nj4Zf4kZAu727N81HnlFCRvDqV
Y05imB04J15DaGbAHlNzunhuJi7121WV/JRXZRW9diE6hwpD8rwqi3FMuRUmy7U9 ZjHUrbE7fJuc3diffUfIHuQZuWcoYDejIbASjcJMHZOpbbPR2ZCYQqUmvg/IgAD6
aFA5poKRAYlo9YtZ3YpFyjGKB6MfCQcB2opuSnQ/gbugV41m67uQ4CDwWLaNRkTb M2GDbvfvLnu1BaCrNMdOxM4j+sLNhm8qqAMxZ/wkZA9Sqhi2EifZwf5jWKNU3Vtx
GlsMBNcHnidg15Bsat5HaB7l250ukrI13Uw1MYdDUzaS3gPfw9aC4F2w0p3U+DPH C/w621efHawDME3WTMunDtjn7Sgm3NP508cz8OgcEcZLwENu8JH5pWR0Y0+qvlPM
80/zePxtroR7T4/+rI136Rl+aMXDMOEGCX1TVP8rjuZzuRyUSUKC8Q== DYpCu2Zh6TBLU6Cfuxl2GigHHBhm8Eza/vE6dVbpyvEozejtVKi+RYskqz8ynYtl
r9NpDkEFcqGFLX/X7fajR4JxzxYx0Ms+CHHBlBLw44eMl1Izb9OBgfUK3a7wJ0Z1
vEmzcVtXZMqKDvqY3wddCcbtpVZhRnAUFgT3/b5ISxQ6xxFg67YQaJ0knuRwOZCI
xSvNsxXb6s5xt8gRx8MY8W1CVW0QSH4gUpKdJFiF/6nYq7h8F1A5QYr34uJn5pa2
bsagCMhCUHKn/hrtTJ/4bC7n7utulXyEZJDGS38nNe5TBmAxeA+MkOAO7AEb8aDo
RylaKT77tmeZXWBtlQGHj0bt2fPOEW3e0WUeNwk4qnKqSGdwbXGFK+yWxgGOxFDT
4NqUjDV7lhj1r3mKEufLIqP6GxAlewpH1uLA+ty2eNfG793pytlyhNikzmkliXex
WnBUYQM6ZBclW0nALHxxOJWZlnBCESgo9lSHMeB7adJXuwaUmqHx4u+yNzaFS6pr
LemBEUCHfLeGFM9E9YbgNe51q5+vXZYN5MZtqyex4AqPdGEGpwXBk43RK79mP84G
QQRAAcs6KMj1/Sl7pmg9acrxskLWljtsnvdCJ8a+VXjLDyp2wks1z2Gnw7cguZdD
Ah4hjH8LDTsEJxOr2DNJu/V9JDPKd0uGyaW0AOanwAn7tszivGddb/WrzImCIMBa
Lb/cqujvS9YsIK6xrq4LMxR5wE6Hol0qs6xO89Y9OpuuRxAYfRUl4nDTg0WjS5Ga
0aoSXB0kOFkEwb3WGq+b26606RBYDKu7RsJoyWoXq42JZ1jkEYKCNeNS8hWh8GKd
-----END RSA PRIVATE KEY----- -----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
MIICXTCCAcYCCQC1Vk/N8qR4AjANBgkqhkiG9w0BAQUFADBzMQswCQYDVQQGEwJB
VDESMBAGA1UECBMJQ2FyaW50aGlhMRIwEAYDVQQHEwlTdC4gSmFrb2IxDzANBgNV
BAoTBkFwcEluZjEPMA0GA1UEAxMGQXBwSW5mMRowGAYJKoZIhvcNAQkBFgthcHBA
aW5mLmNvbTAeFw0wNjAyMjcxMzI3MThaFw0wNjAzMjkxMzI3MThaMHMxCzAJBgNV
BAYTAkFUMRIwEAYDVQQIEwlDYXJpbnRoaWExEjAQBgNVBAcTCVN0LiBKYWtvYjEP
MA0GA1UEChMGQXBwSW5mMQ8wDQYDVQQDEwZBcHBJbmYxGjAYBgkqhkiG9w0BCQEW
C2FwcEBpbmYuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCsFXiPuicN
Im4oJwF8NuaFN+lgYwcZ6dAO3ILIR3kLA2PxF8HSQLfF8J8a4odZhLhctIMAKTxm
k0w8TW5qhL8QLdGzY9vzvkgdKOkan2t3sMeXJAfrM1AphTsmgntAQazGZjOj5p4W
jDnxQ+VXAylqwjHh49eSBxM3wgoscF4iLQIDAQABMA0GCSqGSIb3DQEBBQUAA4GB
AIpfLdXiKchPvFMhQS8xTtXvrw5dVL3yImUMYs4GQi8RrjGmfGB3yMAR7B/b8v4a
+ztfusgWAWiUKuSGTk4S8YB0fsFlmOv0WDr+PyZ4Lui/a8opbyzGE7rqpnF/s0GO
M7uLCNNwIN7WhmxcWV0KZU1wTppoSWPJda1yTbBzF9XP
-----END CERTIFICATE-----

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
// //
// Driver.cpp // Driver.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/testsuite/src/Driver.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/testsuite/src/Driver.cpp#10 $
// //
// Console-based test driver for Poco NetSSL. // Console-based test driver for Poco NetSSL.
// //

View File

@@ -1,7 +1,7 @@
// //
// HTTPSClientSessionTest.cpp // HTTPSClientSessionTest.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/testsuite/src/HTTPSClientSessionTest.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/testsuite/src/HTTPSClientSessionTest.cpp#10 $
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
@@ -31,7 +31,6 @@
#include "HTTPSClientSessionTest.h" #include "HTTPSClientSessionTest.h"
#include "HTTPSClientTestSuite.h"
#include "CppUnit/TestCaller.h" #include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h" #include "CppUnit/TestSuite.h"
#include "Poco/Net/HTTPSClientSession.h" #include "Poco/Net/HTTPSClientSession.h"
@@ -46,6 +45,8 @@
#include "Poco/Net/SecureStreamSocket.h" #include "Poco/Net/SecureStreamSocket.h"
#include "Poco/StreamCopier.h" #include "Poco/StreamCopier.h"
#include "Poco/Exception.h" #include "Poco/Exception.h"
#include "Poco/DateTimeFormatter.h"
#include "Poco/DateTimeFormat.h"
#include "HTTPSTestServer.h" #include "HTTPSTestServer.h"
#include <istream> #include <istream>
#include <ostream> #include <ostream>
@@ -53,11 +54,9 @@
using namespace Poco::Net; using namespace Poco::Net;
using Poco::StreamCopier; using Poco::StreamCopier;
class TestRequestHandler: public HTTPRequestHandler class TestRequestHandler: public HTTPRequestHandler
/// Return a HTML document with the current date and time. /// Return a HTML document with the current date and time.
{ {
@@ -252,40 +251,6 @@ void HTTPSClientSessionTest::testPostLargeChunkedKeepAlive()
} }
void HTTPSClientSessionTest::testPostSmallClose()
{
HTTPSTestServer srv;
HTTPSClientSession s("localhost", srv.port());
HTTPRequest request(HTTPRequest::HTTP_POST, "/echo");
std::string body("this is a random request body");
s.sendRequest(request) << body;
HTTPResponse response;
std::istream& rs = s.receiveResponse(response);
assert (!response.getChunkedTransferEncoding());
assert (response.getContentLength() == HTTPMessage::UNKNOWN_CONTENT_LENGTH);
std::ostringstream ostr;
StreamCopier::copyStream(rs, ostr);
assert (ostr.str() == body);
}
void HTTPSClientSessionTest::testPostLargeClose()
{
HTTPSTestServer srv;
HTTPSClientSession s("localhost", srv.port());
HTTPRequest request(HTTPRequest::HTTP_POST, "/echo");
std::string body(8000, 'x');
s.sendRequest(request) << body;
HTTPResponse response;
std::istream& rs = s.receiveResponse(response);
assert (!response.getChunkedTransferEncoding());
assert (response.getContentLength() == HTTPMessage::UNKNOWN_CONTENT_LENGTH);
std::ostringstream ostr;
StreamCopier::copyStream(rs, ostr);
assert (ostr.str() == body);
}
void HTTPSClientSessionTest::testKeepAlive() void HTTPSClientSessionTest::testKeepAlive()
{ {
HTTPSTestServer srv; HTTPSTestServer srv;
@@ -334,37 +299,40 @@ void HTTPSClientSessionTest::testKeepAlive()
} }
void HTTPSClientSessionTest::testProxy() void HTTPSClientSessionTest::testInterop()
{ {
HTTPSTestServer srv; HTTPSClientSession s("secure.appinf.com");
HTTPSClientSession s(TESTSERVERNAME); HTTPRequest request(HTTPRequest::HTTP_GET, "/public/poco/NetSSL.txt");
s.setProxy("proxy.aon.at", 8080);
HTTPRequest request(HTTPRequest::HTTP_GET, "/");
s.sendRequest(request); s.sendRequest(request);
X509Certificate cert = s.serverCertificate();
HTTPResponse response; HTTPResponse response;
std::istream& rs = s.receiveResponse(response); std::istream& rs = s.receiveResponse(response);
std::ostringstream ostr; std::ostringstream ostr;
StreamCopier::copyStream(rs, ostr); StreamCopier::copyStream(rs, ostr);
assert (ostr.str().length() > 0); std::string str(ostr.str());
assert (str == "This is a test file for NetSSL.\n");
assert (cert.commonName() == "secure.appinf.com");
} }
void HTTPSClientSessionTest::testConnectNB() void HTTPSClientSessionTest::testProxy()
{ {
SecureStreamSocket sock; HTTPSTestServer srv;
sock.connectNB(SocketAddress(TESTSERVERNAME, 443)); HTTPSClientSession s("secure.appinf.com");
char buf[512]; s.setProxy("proxy.aon.at", 8080);
std::string msg("GET / HTTP/1.0\r\n\r\n"); HTTPRequest request(HTTPRequest::HTTP_GET, "/public/poco/NetSSL.txt");
sock.sendBytes(msg.c_str(), (int)msg.length()); s.sendRequest(request);
Socket::SocketList read; X509Certificate cert = s.serverCertificate();
Socket::SocketList write; HTTPResponse response;
Socket::SocketList exec; std::istream& rs = s.receiveResponse(response);
read.push_back(sock); std::ostringstream ostr;
Socket::select(read, write, exec, Poco::Timespan(30, 0) ); StreamCopier::copyStream(rs, ostr);
int rc = sock.receiveBytes(buf, 512); std::string str(ostr.str());
assert (rc > 0); assert (str == "This is a test file for NetSSL.\n");
assert (cert.commonName() == "secure.appinf.com");
} }
void HTTPSClientSessionTest::setUp() void HTTPSClientSessionTest::setUp()
{ {
} }
@@ -387,11 +355,9 @@ CppUnit::Test* HTTPSClientSessionTest::suite()
CppUnit_addTest(pSuite, HTTPSClientSessionTest, testPostSmallChunked); CppUnit_addTest(pSuite, HTTPSClientSessionTest, testPostSmallChunked);
CppUnit_addTest(pSuite, HTTPSClientSessionTest, testPostLargeChunked); CppUnit_addTest(pSuite, HTTPSClientSessionTest, testPostLargeChunked);
CppUnit_addTest(pSuite, HTTPSClientSessionTest, testPostLargeChunkedKeepAlive); CppUnit_addTest(pSuite, HTTPSClientSessionTest, testPostLargeChunkedKeepAlive);
CppUnit_addTest(pSuite, HTTPSClientSessionTest, testPostSmallClose);
CppUnit_addTest(pSuite, HTTPSClientSessionTest, testPostLargeClose);
CppUnit_addTest(pSuite, HTTPSClientSessionTest, testKeepAlive); CppUnit_addTest(pSuite, HTTPSClientSessionTest, testKeepAlive);
CppUnit_addTest(pSuite, HTTPSClientSessionTest, testInterop);
CppUnit_addTest(pSuite, HTTPSClientSessionTest, testProxy); CppUnit_addTest(pSuite, HTTPSClientSessionTest, testProxy);
CppUnit_addTest(pSuite, HTTPSClientSessionTest, testConnectNB);
return pSuite; return pSuite;
} }

View File

@@ -1,7 +1,7 @@
// //
// HTTPSClientSessionTest.h // HTTPSClientSessionTest.h
// //
// $Id: //poco/svn/NetSSL_OpenSSL/testsuite/src/HTTPSClientSessionTest.h#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/testsuite/src/HTTPSClientSessionTest.h#10 $
// //
// Definition of the HTTPSClientSessionTest class. // Definition of the HTTPSClientSessionTest class.
// //
@@ -54,11 +54,9 @@ public:
void testPostSmallChunked(); void testPostSmallChunked();
void testPostLargeChunked(); void testPostLargeChunked();
void testPostLargeChunkedKeepAlive(); void testPostLargeChunkedKeepAlive();
void testPostSmallClose();
void testPostLargeClose();
void testKeepAlive(); void testKeepAlive();
void testInterop();
void testProxy(); void testProxy();
void testConnectNB();
void setUp(); void setUp();
void tearDown(); void tearDown();

View File

@@ -1,7 +1,7 @@
// //
// HTTPSClientTestSuite.cpp // HTTPSClientTestSuite.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/testsuite/src/HTTPSClientTestSuite.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/testsuite/src/HTTPSClientTestSuite.cpp#7 $
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.

View File

@@ -1,7 +1,7 @@
// //
// HTTPSClientTestSuite.h // HTTPSClientTestSuite.h
// //
// $Id: //poco/svn/NetSSL_OpenSSL/testsuite/src/HTTPSClientTestSuite.h#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/testsuite/src/HTTPSClientTestSuite.h#7 $
// //
// Definition of the HTTPSClientTestSuite class. // Definition of the HTTPSClientTestSuite class.
// //
@@ -39,8 +39,6 @@
#include "CppUnit/TestSuite.h" #include "CppUnit/TestSuite.h"
#define TESTSERVERNAME "secure.appinf.com"
class HTTPSClientTestSuite class HTTPSClientTestSuite
{ {
public: public:

View File

@@ -1,7 +1,7 @@
// //
// HTTPSServerTest.cpp // HTTPSServerTest.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/testsuite/src/HTTPSServerTest.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/testsuite/src/HTTPSServerTest.cpp#9 $
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
@@ -192,29 +192,6 @@ void HTTPSServerTest::testChunkedRequest()
} }
void HTTPSServerTest::testClosedRequest()
{
SecureServerSocket svs(0);
HTTPServerParams* pParams = new HTTPServerParams;
pParams->setKeepAlive(false);
HTTPServer srv(new RequestHandlerFactory, svs, pParams);
srv.start();
HTTPSClientSession cs("localhost", svs.address().port());
std::string body(5000, 'x');
HTTPRequest request("POST", "/echoBody");
request.setContentType("text/plain");
cs.sendRequest(request) << body;
HTTPResponse response;
std::string rbody;
cs.receiveResponse(response) >> rbody;
assert (response.getContentLength() == HTTPMessage::UNKNOWN_CONTENT_LENGTH);
assert (response.getContentType() == "text/plain");
assert (!response.getChunkedTransferEncoding());
assert (rbody == body);
}
void HTTPSServerTest::testIdentityRequestKeepAlive() void HTTPSServerTest::testIdentityRequestKeepAlive()
{ {
SecureServerSocket svs(0); SecureServerSocket svs(0);
@@ -284,31 +261,6 @@ void HTTPSServerTest::testChunkedRequestKeepAlive()
} }
void HTTPSServerTest::testClosedRequestKeepAlive()
{
SecureServerSocket svs(0);
HTTPServerParams* pParams = new HTTPServerParams;
pParams->setKeepAlive(true);
HTTPServer srv(new RequestHandlerFactory, svs, pParams);
srv.start();
HTTPSClientSession cs("localhost", svs.address().port());
std::string body(5000, 'x');
HTTPRequest request("POST", "/echoBody");
request.setContentType("text/plain");
cs.sendRequest(request) << body;
HTTPResponse response;
std::string rbody;
cs.receiveResponse(response) >> rbody;
assert (response.getContentLength() == HTTPMessage::UNKNOWN_CONTENT_LENGTH);
assert (response.getContentType() == "text/plain");
assert (!response.getChunkedTransferEncoding());
assert (!response.getKeepAlive());
assert (rbody == body);
int n = (int) rbody.size();
}
void HTTPSServerTest::test100Continue() void HTTPSServerTest::test100Continue()
{ {
SecureServerSocket svs(0); SecureServerSocket svs(0);
@@ -408,10 +360,8 @@ CppUnit::Test* HTTPSServerTest::suite()
CppUnit_addTest(pSuite, HTTPSServerTest, testIdentityRequest); CppUnit_addTest(pSuite, HTTPSServerTest, testIdentityRequest);
CppUnit_addTest(pSuite, HTTPSServerTest, testChunkedRequest); CppUnit_addTest(pSuite, HTTPSServerTest, testChunkedRequest);
CppUnit_addTest(pSuite, HTTPSServerTest, testClosedRequest);
CppUnit_addTest(pSuite, HTTPSServerTest, testIdentityRequestKeepAlive); CppUnit_addTest(pSuite, HTTPSServerTest, testIdentityRequestKeepAlive);
CppUnit_addTest(pSuite, HTTPSServerTest, testChunkedRequestKeepAlive); CppUnit_addTest(pSuite, HTTPSServerTest, testChunkedRequestKeepAlive);
CppUnit_addTest(pSuite, HTTPSServerTest, testClosedRequestKeepAlive);
CppUnit_addTest(pSuite, HTTPSServerTest, test100Continue); CppUnit_addTest(pSuite, HTTPSServerTest, test100Continue);
CppUnit_addTest(pSuite, HTTPSServerTest, testRedirect); CppUnit_addTest(pSuite, HTTPSServerTest, testRedirect);
CppUnit_addTest(pSuite, HTTPSServerTest, testAuth); CppUnit_addTest(pSuite, HTTPSServerTest, testAuth);

View File

@@ -1,7 +1,7 @@
// //
// HTTPSServerTest.h // HTTPSServerTest.h
// //
// $Id: //poco/svn/NetSSL_OpenSSL/testsuite/src/HTTPSServerTest.h#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/testsuite/src/HTTPSServerTest.h#8 $
// //
// Definition of the HTTPSServerTest class. // Definition of the HTTPSServerTest class.
// //
@@ -48,10 +48,8 @@ public:
void testIdentityRequest(); void testIdentityRequest();
void testChunkedRequest(); void testChunkedRequest();
void testClosedRequest();
void testIdentityRequestKeepAlive(); void testIdentityRequestKeepAlive();
void testChunkedRequestKeepAlive(); void testChunkedRequestKeepAlive();
void testClosedRequestKeepAlive();
void test100Continue(); void test100Continue();
void testRedirect(); void testRedirect();
void testAuth(); void testAuth();

View File

@@ -1,7 +1,7 @@
// //
// HTTPSServerTestSuite.cpp // HTTPSServerTestSuite.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/testsuite/src/HTTPSServerTestSuite.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/testsuite/src/HTTPSServerTestSuite.cpp#7 $
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.

View File

@@ -1,7 +1,7 @@
// //
// HTTPSServerTestSuite.h // HTTPSServerTestSuite.h
// //
// $Id: //poco/svn/NetSSL_OpenSSL/testsuite/src/HTTPSServerTestSuite.h#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/testsuite/src/HTTPSServerTestSuite.h#7 $
// //
// Definition of the HTTPSServerTestSuite class. // Definition of the HTTPSServerTestSuite class.
// //

View File

@@ -1,7 +1,7 @@
// //
// HTTPSStreamFactoryTest.cpp // HTTPSStreamFactoryTest.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/testsuite/src/HTTPSStreamFactoryTest.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/testsuite/src/HTTPSStreamFactoryTest.cpp#8 $
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.
@@ -31,7 +31,6 @@
#include "HTTPSStreamFactoryTest.h" #include "HTTPSStreamFactoryTest.h"
#include "HTTPSClientTestSuite.h"
#include "CppUnit/TestCaller.h" #include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h" #include "CppUnit/TestSuite.h"
#include "Poco/Net/HTTPSStreamFactory.h" #include "Poco/Net/HTTPSStreamFactory.h"
@@ -104,7 +103,7 @@ void HTTPSStreamFactoryTest::testProxy()
{ {
HTTPSTestServer server; HTTPSTestServer server;
HTTPSStreamFactory factory("proxy.aon.at", 8080); HTTPSStreamFactory factory("proxy.aon.at", 8080);
URI uri(std::string("https://") + TESTSERVERNAME + "/"); URI uri("https://sourceforge.net/");
std::auto_ptr<std::istream> pStr(factory.open(uri)); std::auto_ptr<std::istream> pStr(factory.open(uri));
std::ostringstream ostr; std::ostringstream ostr;
StreamCopier::copyStream(*pStr.get(), ostr); StreamCopier::copyStream(*pStr.get(), ostr);

View File

@@ -1,7 +1,7 @@
// //
// HTTPSStreamFactoryTest.h // HTTPSStreamFactoryTest.h
// //
// $Id: //poco/svn/NetSSL_OpenSSL/testsuite/src/HTTPSStreamFactoryTest.h#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/testsuite/src/HTTPSStreamFactoryTest.h#7 $
// //
// Definition of the HTTPSStreamFactoryTest class. // Definition of the HTTPSStreamFactoryTest class.
// //

View File

@@ -1,7 +1,7 @@
// //
// HTTPSTestServer.cpp // HTTPSTestServer.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/testsuite/src/HTTPSTestServer.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/testsuite/src/HTTPSTestServer.cpp#9 $
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.

View File

@@ -1,7 +1,7 @@
// //
// HTTPSTestServer.h // HTTPSTestServer.h
// //
// $Id: //poco/svn/NetSSL_OpenSSL/testsuite/src/HTTPSTestServer.h#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/testsuite/src/HTTPSTestServer.h#7 $
// //
// Definition of the HTTPSTestServer class. // Definition of the HTTPSTestServer class.
// //

View File

@@ -1,7 +1,7 @@
// //
// OpenSSLTestSuite.cpp // OpenSSLTestSuite.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/testsuite/src/NetSSLTestSuite.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/testsuite/src/NetSSLTestSuite.cpp#7 $
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.

View File

@@ -1,7 +1,7 @@
// //
// NetSSLTestSuite.h // NetSSLTestSuite.h
// //
// $Id: //poco/svn/NetSSL_OpenSSL/testsuite/src/NetSSLTestSuite.h#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/testsuite/src/NetSSLTestSuite.h#7 $
// //
// Definition of the NetSSLTestSuite class. // Definition of the NetSSLTestSuite class.
// //

View File

@@ -1,7 +1,7 @@
// //
// TCPServerTest.cpp // TCPServerTest.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/testsuite/src/TCPServerTest.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/testsuite/src/TCPServerTest.cpp#7 $
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.

View File

@@ -1,7 +1,7 @@
// //
// TCPServerTest.h // TCPServerTest.h
// //
// $Id: //poco/svn/NetSSL_OpenSSL/testsuite/src/TCPServerTest.h#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/testsuite/src/TCPServerTest.h#7 $
// //
// Definition of the TCPServerTest class. // Definition of the TCPServerTest class.
// //

View File

@@ -1,7 +1,7 @@
// //
// TCPServerTestSuite.cpp // TCPServerTestSuite.cpp
// //
// $Id: //poco/svn/NetSSL_OpenSSL/testsuite/src/TCPServerTestSuite.cpp#1 $ // $Id: //poco/Main/NetSSL_OpenSSL/testsuite/src/TCPServerTestSuite.cpp#7 $
// //
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors. // and Contributors.

Some files were not shown because too many files have changed in this diff Show More