E-MailRelay
gssl.h
Go to the documentation of this file.
1 //
2 // Copyright (C) 2001-2018 Graeme Walker <graeme_walker@users.sourceforge.net>
3 //
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with this program. If not, see <http://www.gnu.org/licenses/>.
16 // ===
17 ///
18 /// \file gssl.h
19 ///
20 /// An interface to an underlying TLS library.
21 ///
22 
23 #ifndef G_SSL__H
24 #define G_SSL__H
25 
26 #include "gdef.h"
27 #include "gstrings.h"
28 #include "greadwrite.h"
29 #include <string>
30 #include <utility>
31 
32 namespace GSsl
33 {
34  class Library ;
35  class Profile ;
36  class Protocol ;
37  class Digester ;
38  class LibraryImpBase ;
39  class ProtocolImpBase ;
40  class DigesterImpBase ;
41 }
42 
43 /// \class GSsl::Protocol
44 /// A TLS protocol class. A protocol object should be constructed for each
45 /// secure socket. The Protocol::connect() and Protocol::accept() methods
46 /// are used to link the connection's i/o methods with the Protocol object.
47 /// Event handling for the connection is performed by the client code
48 /// according to the result codes from read(), write(), connect() and
49 /// accept().
50 ///
51 /// Client code will generally need separate states to reflect an incomplete
52 /// read(), write(), connect() or accept() in order that they can be retried.
53 /// The distinction between a return code of Result_read or Result_write
54 /// should dictate whether the connection is put into the event loop's read
55 /// list or write list but it should not influence the resulting state; in
56 /// each state socket read events and write events can be handled identically,
57 /// by retrying the incomplete function call.
58 ///
59 /// The protocol is half-duplex in the sense that it is not possible to read()
60 /// data while a write() is incomplete or write() data while a read() is
61 /// incomplete. (Nor is it allowed to issue a second call while the first is
62 /// still incomplete.)
63 ///
65 {
66 public:
67  enum Result // Result enumeration for GSsl::Protocol i/o methods.
68  {
69  Result_ok ,
70  Result_read ,
71  Result_write ,
72  Result_error ,
73  Result_more
74  } ;
75 
76  explicit Protocol( const Profile & , const std::string & peer_certificate_name = std::string() ,
77  const std::string & peer_host_name = std::string() ) ;
78  ///< Constructor.
79  ///<
80  ///< The optional "peer-certificate-name" parameter is used as an
81  ///< additional check on the peer certificate. In the simplest case
82  ///< a client passes the server's domain name and this is checked for
83  ///< an exact match against the certificate's subject CNAME (eg.
84  ///< "CN=*.example.com"). A valid CA database is required. If the
85  ///< peer-certificate-name parameter is empty then a default value
86  ///< is taken from the profile (see Library::addProfile()).
87  ///<
88  ///< The optional "peer-host-name" parameter is included in the
89  ///< TLS handshake to indicate the required peer hostname. This
90  ///< is typcially used by clients for server-name-identification
91  ///< (SNI) when connecting to virtual hosts, allowing servers to
92  ///< assume the appropriate identity. If the peer-host-name
93  ///< parameter is empty then a default value is taken from the
94  ///< profile (see Library::addProfile()).
95  ///<
96  ///< Some underlying libraries treat peer-certificate-name and
97  ///< peer-host-name to be the same, using wildcard matching of
98  ///< the certificate CNAME against the peer-host-name.
99 
100  ~Protocol() ;
101  ///< Destructor.
102 
103  Result connect( G::ReadWrite & io ) ;
104  ///< Starts the protocol actively (as a client).
105 
106  Result accept( G::ReadWrite & io ) ;
107  ///< Starts the protocol passively (as a server).
108 
109  Result stop() ;
110  ///< Initiates the protocol shutdown.
111 
112  Result read( char * buffer , size_t buffer_size_in , ssize_t & data_size_out ) ;
113  ///< Reads user data into the supplied buffer.
114  ///<
115  ///< Returns Result_read if there is not enough transport data to
116  ///< complete the internal TLS data packet. In this case the file
117  ///< descriptor should remain in the select() read list and the
118  ///< Protocol::read() should be retried using the same parameters
119  ///< once the file descriptor is ready to be read.
120  ///<
121  ///< Returns Result_write if the TLS layer tried to write to the
122  ///< file descriptor and had flow control asserted. In this case
123  ///< the file descriptor should be added to the select() write
124  ///< list and the Protocol::read() should be retried using the
125  ///< same parameters once the file descriptor is ready to be
126  ///< written.
127  ///<
128  ///< Returns Result_ok if the internal TLS data packet is complete
129  ///< and it has been completely deposited in the supplied buffer.
130  ///<
131  ///< Returns Result_more if the internal TLS data packet is complete
132  ///< and the supplied buffer was too small to take it all. In this
133  ///< case there will be no read event to trigger more read()s so
134  ///< call read() again imediately.
135  ///<
136  ///< Returns Result_error if the transport connnection was lost
137  ///< or if the TLS session was shut down by the peer or if there
138  ///< was an error.
139 
140  Result write( const char * buffer , size_t data_size_in , ssize_t & data_size_out ) ;
141  ///< Writes user data.
142  ///<
143  ///< Returns Result_ok if fully sent.
144  ///<
145  ///< Returns Result_read if the TLS layer needs more transport
146  ///< data (eg. for a renegotiation). The write() should be repeated
147  ///< using the same parameters on the file descriptor's next
148  ///< readable event.
149  ///<
150  ///< Returns Result_write if the TLS layer was blocked in
151  ///< writing transport data. The write() should be repeated
152  ///< using the same parameters on the file descriptor's next
153  ///< writable event.
154  ///<
155  ///< Never returns Result_more.
156  ///<
157  ///< Returns Result_error if the transport connnection was lost
158  ///< or if the TLS session was shut down by the peer or on error.
159 
160  static std::string str( Result result ) ;
161  ///< Converts a result enumeration into a printable string.
162  ///< Used in logging and diagnostics.
163 
164  std::string peerCertificate() const ;
165  ///< Returns the peer certificate in PEM format. This can be
166  ///< interpreted using "openssl x509 -in ... -noout -text".
167 
168  bool verified() const ;
169  ///< Returns true if the peer certificate has been verified.
170 
171  std::string peerCertificateChain() const ;
172  ///< Returns the peer certificate chain in PEM format, starting
173  ///< with the peer certificate and progressing towards the
174  ///< root CA.
175  ///<
176  ///< This is not supported by all underlying TLS libraries; the
177  ///< returned string may be just the peerCertificate().
178 
179 private:
180  Protocol( const Protocol & ) ; // not implemented
181  void operator=( const Protocol & ) ; // not implemented
182 
183 private:
184  ProtocolImpBase * m_imp ;
185 } ;
186 
187 /// \class GSsl::Digester
188 /// Returns an object that can perform a cryptographic hash.
189 /// Use add() one or more times, then call either state() or
190 /// value() and discard. The state() string can be passed
191 /// to the Library factory method to restart the digest
192 /// from the intermediate state.
193 ///
195 {
196 public:
197  explicit Digester( DigesterImpBase * ) ;
198  ///< Constructor, used by the Library class.
199 
200  size_t blocksize() const ;
201  ///< Returns the hash function's block size in bytes.
202 
203  size_t valuesize() const ;
204  ///< Returns the hash function's value size in bytes.
205 
206  size_t statesize() const ;
207  ///< Returns the size of the state() string in bytes,
208  ///< or zero if state() is not implemented.
209 
210  void add( const std::string & ) ;
211  ///< Adds data of arbitrary size.
212 
213  std::string state() ;
214  ///< Returns the intermediate state. The state string can be
215  ///< persisted and reused across different implementations, so
216  ///< it is standardised as some number of 32-bit little-endian
217  ///< values making up valuesize() bytes, followed by one
218  ///< 32-bit little-endian value holding the total add()ed
219  ///< size.
220 
221  std::string value() ;
222  ///< Returns the hash value.
223 
224 private:
225  shared_ptr<DigesterImpBase> m_imp ;
226 } ;
227 
228 /// \class GSsl::Library
229 /// A singleton class for initialising the underlying TLS library.
230 /// The library is configured with one or more named "profiles", and
231 /// Protocol objects are constructed with reference to a particular
232 /// profile. Typical profile names are "server" and "client".
233 ///
235 {
236 public:
237  typedef void (*LogFn)( int , const std::string & ) ;
238 
239  explicit Library( bool active = true , const std::string & library_config = std::string() ,
240  LogFn = Library::log , bool verbose = true ) ;
241  ///< Constructor.
242  ///<
243  ///< The 'active' parameter can be set to false as an optimisation if the
244  ///< library is not going to be used; calls to addProfile() will do
245  ///< nothing, calls to hasProfile() will return false, and calls to
246  ///< profile() will throw.
247  ///<
248  ///< The library-config parameter should be empty by default; the format
249  ///< and interpretation are undefined at this interface.
250 
251  ~Library() ;
252  ///< Destructor. Cleans up the underlying TLS library.
253 
254  static void log( int level , const std::string & line ) ;
255  ///< The default logging callback function, where the level is 1 for
256  ///< debug, 2 for info, 3 for warnings, and 4 for errors. There
257  ///< will be no level 1 logging if the constructor's 'verbose'
258  ///< flag was false.
259 
260  static Library * instance() ;
261  ///< Returns a pointer to a library object, if any.
262 
263  void addProfile( const std::string & profile_name , bool is_server_profile ,
264  const std::string & key_file = std::string() , const std::string & cert_file = std::string() ,
265  const std::string & ca_path = std::string() ,
266  const std::string & default_peer_certificate_name = std::string() ,
267  const std::string & default_peer_host_name = std::string() ,
268  const std::string & profile_config = std::string() ) ;
269  ///< Creates a named Profile object that can be retrieved by profile().
270  ///<
271  ///< A typical application will have two profiles named "client" and "server".
272  ///< The "is-server-profile" flag indicates whether Protocol::connect()
273  ///< or Protocol::accept() will be used.
274  ///<
275  ///< The "key-file" and "cert-file" parameters point to a PEM files containing
276  ///< our own key and certificate, and this can be the same file if it contains
277  ///< both. These are required if acting as a server, but if not supplied
278  ///< this method will succeed with the failures occuring in any subsequent
279  ///< server-side session setup.
280  ///<
281  ///< The "ca-path" parameter points to a file or directory containing a
282  ///< database of CA certificates used for peer certificate verification.
283  ///< If this is "<none>" then a server will not ask its client for a
284  ///< certificate; if it is empty then the peer certificate will be requested,
285  ///< but the server will not require a certificate from the client, and
286  ///< any certificate received will not be not verified; if it is a file
287  ///< system path or "<default>" then a peer certificate will be required
288  ///< and it will be verified against the CA database.
289  ///<
290  ///< The "default-peer-certificate-name" parameter is used by Protocol
291  ///< objects created from this Profile in cases when the Protocol does not
292  ///< get a more specific peer-certificate-name passed in its constructor.
293  ///<
294  ///< Similarly the "default-peer-host-name" is used by Protocol objects
295  ///< if they do not get a more specific peer-host-name in their constructor.
296  ///<
297  ///< The "profile-config" parameter is used for any additional configuration
298  ///< items; the format and interpretation are undefined at this interface.
299 
300  bool hasProfile( const std::string & profile_name ) const ;
301  ///< Returns true if the named profile has been add()ed.
302 
303  const Profile & profile( const std::string & profile_name ) const ;
304  ///< Returns an opaque reference to the named profile. The profile
305  ///< can be used to construct a protocol instance.
306 
307  bool enabled() const ;
308  ///< Returns true if this is a real TLS library and the constructor's active
309  ///< parameter was set.
310 
311  std::string id() const ;
312  ///< Returns the TLS library name and version.
313 
314  static LibraryImpBase & impstance() ;
315  ///< Returns a reference to the pimple object when enabled(). Used in
316  ///< implementations. Throws if none.
317 
318  static bool real() ;
319  ///< Returns true if this is a real TLS library.
320 
321  static std::string credit( const std::string & prefix , const std::string & eol , const std::string & eot ) ;
322  ///< Returns a multi-line library credit for all available TLS libraries.
323 
324  static std::string ids() ;
325  ///< Returns a concatenation of all available TLS library names and versions.
326 
327  static bool enabledAs( const std::string & profile_name ) ;
328  ///< A static convenience function that returns true if there is an
329  ///< enabled() Library instance() that has the named profile.
330 
331  static G::StringArray digesters( bool require_state = false ) ;
332  ///< Returns a list of hash function names (such as "MD5") that the TLS
333  ///< library can do, ordered roughly from strongest to weakest. Returns
334  ///< the empty list if there is no Library instance. If the boolean
335  ///< parameter is true then the returned list is limited to those
336  ///< hash functions that can be initialised with an intermediate
337  ///< state.
338 
339  Digester digester( const std::string & name , const std::string & state = std::string() ) const ;
340  ///< Returns a digester object.
341 
342 private:
343  Library( const Library & ) ;
344  void operator=( const Library & ) ;
345  const LibraryImpBase & imp() const ;
346  LibraryImpBase & imp() ;
347  static LibraryImpBase * newLibraryImp( G::StringArray & , Library::LogFn , bool ) ;
348 
349 private:
350  static Library * m_this ;
351  LibraryImpBase * m_imp ;
352 } ;
353 
354 /// \class GSsl::LibraryImpBase
355 /// A base interface for GSsl::Library pimple classes. A common base allows
356 /// for multiple TLS libraries to be built in and then selected at run-time.
357 ///
359 {
360 public:
361  virtual ~LibraryImpBase() ;
362  ///< Destructor.
363 
364  virtual std::string id() const = 0 ;
365  ///< Implements Library::id().
366 
367  virtual void addProfile( const std::string & , bool , const std::string & , const std::string & ,
368  const std::string & , const std::string & , const std::string & , const std::string & ) = 0 ;
369  ///< Implements Library::addProfile().
370 
371  virtual bool hasProfile( const std::string & profile_name ) const = 0 ;
372  ///< Implements Library::hasProfile().
373 
374  virtual const Profile & profile( const std::string & profile_name ) const = 0 ;
375  ///< Implements Library::profile().
376 
377  virtual G::StringArray digesters( bool ) const = 0 ;
378  ///< Implements Library::digesters().
379 
380  virtual Digester digester( const std::string & , const std::string & ) const = 0 ;
381  ///< Implements Library::digester().
382 
383  static bool consume( G::StringArray & list , const std::string & item ) ;
384  ///< A convenience function that removes the item from
385  ///< the list and returns true iff is was removed.
386 } ;
387 
388 /// \class GSsl::Profile
389 /// A base interface for profile classes that work with concrete classes
390 /// derived from GSsl::LibraryImpBase and GSsl::ProtocolImpBase.
391 ///
393 {
394 public:
395  virtual ~Profile() ;
396  ///< Destructor.
397 
398  virtual ProtocolImpBase * newProtocol( const std::string & , const std::string & ) const = 0 ;
399  ///< Factory method for a new Protocol object on the heap.
400 } ;
401 
402 /// \class GSsl::ProtocolImpBase
403 /// A base interface for GSsl::Protocol pimple classes.
404 ///
406 {
407 public:
408  virtual ~ProtocolImpBase() ;
409  ///< Destructor.
410 
411  virtual Protocol::Result connect( G::ReadWrite & ) = 0 ;
412  ///< Implements Protocol::connect().
413 
414  virtual Protocol::Result accept( G::ReadWrite & ) = 0 ;
415  ///< Implements Protocol::accept().
416 
417  virtual Protocol::Result stop() = 0 ;
418  ///< Implements Protocol::stop().
419 
420  virtual Protocol::Result read( char * , size_t , ssize_t & ) = 0 ;
421  ///< Implements Protocol::read().
422 
423  virtual Protocol::Result write( const char * , size_t , ssize_t & ) = 0 ;
424  ///< Implements Protocol::write().
425 
426  virtual std::string peerCertificate() const = 0 ;
427  ///< Implements Protocol::peerCertificate().
428 
429  virtual std::string peerCertificateChain() const = 0 ;
430  ///< Implements Protocol::peerCertificateChain().
431 
432  virtual bool verified() const = 0 ;
433  ///< Implements Protocol::verified().
434 } ;
435 
436 /// \class GSsl::DigesterImpBase
437 /// A base interface for GSsl::Digester pimple classes.
438 ///
440 {
441 public:
442  virtual ~DigesterImpBase() ;
443  ///< Destructor.
444 
445  virtual void add( const std::string & ) = 0 ;
446  ///< Implements Digester::add().
447 
448  virtual std::string value() = 0 ;
449  ///< Implements Digester::value().
450 
451  virtual std::string state() = 0 ;
452  ///< Implements Digester::state().
453 
454  virtual size_t blocksize() const = 0 ;
455  ///< Implements Digester::blocksize().
456 
457  virtual size_t valuesize() const = 0 ;
458  ///< Implements Digester::valuesize().
459 
460  virtual size_t statesize() const = 0 ;
461  ///< Implements Digester::statesize().
462 } ;
463 
464 #endif
A base interface for profile classes that work with concrete classes derived from GSsl::LibraryImpBas...
Definition: gssl.h:392
static Library * instance()
Returns a pointer to a library object, if any.
Definition: gssl.cpp:72
std::string peerCertificateChain() const
Returns the peer certificate chain in PEM format, starting with the peer certificate and progressing ...
Definition: gssl.cpp:172
virtual size_t blocksize() const =0
Implements Digester::blocksize().
Digester digester(const std::string &name, const std::string &state=std::string()) const
Returns a digester object.
Definition: gssl.cpp:150
An abstract interface for reading and writing from a non-blocking i/o channel.
Definition: greadwrite.h:49
A base interface for GSsl::Protocol pimple classes.
Definition: gssl.h:405
virtual const Profile & profile(const std::string &profile_name) const =0
Implements Library::profile().
virtual ~LibraryImpBase()
Destructor.
Definition: gssl.cpp:255
virtual ProtocolImpBase * newProtocol(const std::string &, const std::string &) const =0
Factory method for a new Protocol object on the heap.
std::string state()
Returns the intermediate state.
Definition: gssl.cpp:233
static G::StringArray digesters(bool require_state=false)
Returns a list of hash function names (such as "MD5") that the TLS library can do, ordered roughly from strongest to weakest.
Definition: gssl.cpp:145
bool hasProfile(const std::string &profile_name) const
Returns true if the named profile has been add()ed.
Definition: gssl.cpp:97
virtual G::StringArray digesters(bool) const =0
Implements Library::digesters().
virtual Protocol::Result read(char *, size_t, ssize_t &)=0
Implements Protocol::read().
A TLS protocol class.
Definition: gssl.h:64
std::vector< std::string > StringArray
A std::vector of std::strings.
Definition: gstrings.h:33
static bool enabledAs(const std::string &profile_name)
A static convenience function that returns true if there is an enabled() Library instance() that has ...
Definition: gssl.cpp:109
virtual std::string peerCertificate() const =0
Implements Protocol::peerCertificate().
virtual std::string value()=0
Implements Digester::value().
static std::string str(Result result)
Converts a result enumeration into a printable string.
Definition: gssl.cpp:182
void addProfile(const std::string &profile_name, bool is_server_profile, const std::string &key_file=std::string(), const std::string &cert_file=std::string(), const std::string &ca_path=std::string(), const std::string &default_peer_certificate_name=std::string(), const std::string &default_peer_host_name=std::string(), const std::string &profile_config=std::string())
Creates a named Profile object that can be retrieved by profile().
Definition: gssl.cpp:87
virtual ~Profile()
Destructor.
Definition: gssl.cpp:275
~Library()
Destructor. Cleans up the underlying TLS library.
Definition: gssl.cpp:60
static void log(int level, const std::string &line)
The default logging callback function, where the level is 1 for debug, 2 for info, 3 for warnings, and 4 for errors.
Definition: gssl.cpp:135
A base interface for GSsl::Digester pimple classes.
Definition: gssl.h:439
virtual Protocol::Result accept(G::ReadWrite &)=0
Implements Protocol::accept().
static LibraryImpBase & impstance()
Returns a reference to the pimple object when enabled().
Definition: gssl.cpp:114
Protocol(const Profile &, const std::string &peer_certificate_name=std::string(), const std::string &peer_host_name=std::string())
Constructor.
Definition: gssl.cpp:157
virtual Protocol::Result connect(G::ReadWrite &)=0
Implements Protocol::connect().
virtual size_t statesize() const =0
Implements Digester::statesize().
Result stop()
Initiates the protocol shutdown.
Definition: gssl.cpp:211
virtual std::string peerCertificateChain() const =0
Implements Protocol::peerCertificateChain().
Returns an object that can perform a cryptographic hash.
Definition: gssl.h:194
virtual std::string id() const =0
Implements Library::id().
Result read(char *buffer, size_t buffer_size_in, ssize_t &data_size_out)
Reads user data into the supplied buffer.
Definition: gssl.cpp:201
Result accept(G::ReadWrite &io)
Starts the protocol passively (as a server).
Definition: gssl.cpp:196
static bool consume(G::StringArray &list, const std::string &item)
A convenience function that removes the item from the list and returns true iff is was removed...
Definition: gssl.cpp:259
A base interface for GSsl::Library pimple classes.
Definition: gssl.h:358
std::string value()
Returns the hash value.
Definition: gssl.cpp:228
Result connect(G::ReadWrite &io)
Starts the protocol actively (as a client).
Definition: gssl.cpp:191
static std::string credit(const std::string &prefix, const std::string &eol, const std::string &eot)
Returns a multi-line library credit for all available TLS libraries.
Definition: gssl_none.cpp:84
Digester(DigesterImpBase *)
Constructor, used by the Library class.
Definition: gssl.cpp:218
const Profile & profile(const std::string &profile_name) const
Returns an opaque reference to the named profile.
Definition: gssl.cpp:102
virtual void addProfile(const std::string &, bool, const std::string &, const std::string &, const std::string &, const std::string &, const std::string &, const std::string &)=0
Implements Library::addProfile().
std::string peerCertificate() const
Returns the peer certificate in PEM format.
Definition: gssl.cpp:167
virtual bool verified() const =0
Implements Protocol::verified().
size_t valuesize() const
Returns the hash function's value size in bytes.
Definition: gssl.cpp:243
Library(bool active=true, const std::string &library_config=std::string(), LogFn=Library::log, bool verbose=true)
Constructor.
Definition: gssl.cpp:30
void add(const std::string &)
Adds data of arbitrary size.
Definition: gssl.cpp:223
static std::string ids()
Returns a concatenation of all available TLS library names and versions.
Definition: gssl_none.cpp:89
virtual std::string state()=0
Implements Digester::state().
Result write(const char *buffer, size_t data_size_in, ssize_t &data_size_out)
Writes user data.
Definition: gssl.cpp:206
Definition: gbase64.cpp:27
virtual Protocol::Result write(const char *, size_t, ssize_t &)=0
Implements Protocol::write().
virtual Protocol::Result stop()=0
Implements Protocol::stop().
A singleton class for initialising the underlying TLS library.
Definition: gssl.h:234
static bool real()
Returns true if this is a real TLS library.
Definition: gssl.cpp:67
~Protocol()
Destructor.
Definition: gssl.cpp:162
size_t statesize() const
Returns the size of the state() string in bytes, or zero if state() is not implemented.
Definition: gssl.cpp:248
virtual ~DigesterImpBase()
Destructor.
Definition: gssl.cpp:283
bool enabled() const
Returns true if this is a real TLS library and the constructor's active parameter was set...
Definition: gssl.cpp:77
TLS/SSL transport layer security classes.
Definition: gssl.h:32
virtual size_t valuesize() const =0
Implements Digester::valuesize().
size_t blocksize() const
Returns the hash function's block size in bytes.
Definition: gssl.cpp:238
bool verified() const
Returns true if the peer certificate has been verified.
Definition: gssl.cpp:177
virtual bool hasProfile(const std::string &profile_name) const =0
Implements Library::hasProfile().
virtual Digester digester(const std::string &, const std::string &) const =0
Implements Library::digester().
virtual void add(const std::string &)=0
Implements Digester::add().
std::string id() const
Returns the TLS library name and version.
Definition: gssl.cpp:82
virtual ~ProtocolImpBase()
Destructor.
Definition: gssl.cpp:279