MySQL 5.6.14 Source Code Document
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
yassl_int.cpp
1 /* Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
2 
3  This program is free software; you can redistribute it and/or modify
4  it under the terms of the GNU General Public License as published by
5  the Free Software Foundation; version 2 of the License.
6 
7  This program is distributed in the hope that it will be useful,
8  but WITHOUT ANY WARRANTY; without even the implied warranty of
9  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  GNU General Public License for more details.
11 
12  You should have received a copy of the GNU General Public License
13  along with this program; if not, write to the Free Software
14  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */
15 
16 /* yaSSL internal source implements SSL supporting types not specified in the
17  * draft along with type conversion functions.
18  */
19 
20 // First include (the generated) my_config.h, to get correct platform defines.
21 #include "my_config.h"
22 #ifdef __WIN__
23 #include<Windows.h>
24 #else
25 #include <pthread.h>
26 #endif
27 
28 #include "runtime.hpp"
29 #include "yassl_int.hpp"
30 #include "handshake.hpp"
31 #include "timer.hpp"
32 
33 #ifdef HAVE_LIBZ
34  #include "zlib.h"
35 #endif
36 
37 
38 #ifdef YASSL_PURE_C
39 
40  void* operator new(size_t sz, yaSSL::new_t)
41  {
42  void* ptr = malloc(sz ? sz : 1);
43  if (!ptr) abort();
44 
45  return ptr;
46  }
47 
48 
49  void operator delete(void* ptr, yaSSL::new_t)
50  {
51  if (ptr) free(ptr);
52  }
53 
54 
55  void* operator new[](size_t sz, yaSSL::new_t nt)
56  {
57  return ::operator new(sz, nt);
58  }
59 
60 
61  void operator delete[](void* ptr, yaSSL::new_t nt)
62  {
63  ::operator delete(ptr, nt);
64  }
65 
66  namespace yaSSL {
67 
68  new_t ys; // for yaSSL library new
69 
70  }
71 
72 #endif // YASSL_PURE_C
73 
74 /* for the definition of get_tty_password() */
75 #include <mysql/get_password.h>
76 
77 namespace yaSSL {
78 
79 
80 
81 
82 
83 
84 // convert a 32 bit integer into a 24 bit one
85 void c32to24(uint32 u32, uint24& u24)
86 {
87  u24[0] = (u32 >> 16) & 0xff;
88  u24[1] = (u32 >> 8) & 0xff;
89  u24[2] = u32 & 0xff;
90 }
91 
92 
93 // convert a 24 bit integer into a 32 bit one
94 void c24to32(const uint24 u24, uint32& u32)
95 {
96  u32 = 0;
97  u32 = (u24[0] << 16) | (u24[1] << 8) | u24[2];
98 }
99 
100 
101 // convert with return for ease of use
102 uint32 c24to32(const uint24 u24)
103 {
104  uint32 ret;
105  c24to32(u24, ret);
106 
107  return ret;
108 }
109 
110 
111 // using a for opaque since underlying type is unsgined char and o is not a
112 // good leading identifier
113 
114 // convert opaque to 16 bit integer
115 void ato16(const opaque* c, uint16& u16)
116 {
117  u16 = 0;
118  u16 = (c[0] << 8) | (c[1]);
119 }
120 
121 
122 // convert (copy) opaque to 24 bit integer
123 void ato24(const opaque* c, uint24& u24)
124 {
125  u24[0] = c[0];
126  u24[1] = c[1];
127  u24[2] = c[2];
128 }
129 
130 
131 // convert 16 bit integer to opaque
132 void c16toa(uint16 u16, opaque* c)
133 {
134  c[0] = (u16 >> 8) & 0xff;
135  c[1] = u16 & 0xff;
136 }
137 
138 
139 // convert 24 bit integer to opaque
140 void c24toa(const uint24 u24, opaque* c)
141 {
142  c[0] = u24[0];
143  c[1] = u24[1];
144  c[2] = u24[2];
145 }
146 
147 
148 // convert 32 bit integer to opaque
149 void c32toa(uint32 u32, opaque* c)
150 {
151  c[0] = (u32 >> 24) & 0xff;
152  c[1] = (u32 >> 16) & 0xff;
153  c[2] = (u32 >> 8) & 0xff;
154  c[3] = u32 & 0xff;
155 }
156 
157 
158 States::States() : recordLayer_(recordReady), handshakeLayer_(preHandshake),
159  clientState_(serverNull), serverState_(clientNull),
160  connectState_(CONNECT_BEGIN), acceptState_(ACCEPT_BEGIN),
161  what_(no_error) {}
162 
163 const RecordLayerState& States::getRecord() const
164 {
165  return recordLayer_;
166 }
167 
168 
169 const HandShakeState& States::getHandShake() const
170 {
171  return handshakeLayer_;
172 }
173 
174 
175 const ClientState& States::getClient() const
176 {
177  return clientState_;
178 }
179 
180 
181 const ServerState& States::getServer() const
182 {
183  return serverState_;
184 }
185 
186 
187 const ConnectState& States::GetConnect() const
188 {
189  return connectState_;
190 }
191 
192 
193 const AcceptState& States::GetAccept() const
194 {
195  return acceptState_;
196 }
197 
198 
199 const char* States::getString() const
200 {
201  return errorString_;
202 }
203 
204 
205 YasslError States::What() const
206 {
207  return what_;
208 }
209 
210 
211 RecordLayerState& States::useRecord()
212 {
213  return recordLayer_;
214 }
215 
216 
217 HandShakeState& States::useHandShake()
218 {
219  return handshakeLayer_;
220 }
221 
222 
223 ClientState& States::useClient()
224 {
225  return clientState_;
226 }
227 
228 
229 ServerState& States::useServer()
230 {
231  return serverState_;
232 }
233 
234 
235 ConnectState& States::UseConnect()
236 {
237  return connectState_;
238 }
239 
240 
241 AcceptState& States::UseAccept()
242 {
243  return acceptState_;
244 }
245 
246 
247 char* States::useString()
248 {
249  return errorString_;
250 }
251 
252 
253 void States::SetError(YasslError ye)
254 {
255  what_ = ye;
256 }
257 
258 
259 sslFactory::sslFactory() :
260  messageFactory_(InitMessageFactory),
261  handShakeFactory_(InitHandShakeFactory),
262  serverKeyFactory_(InitServerKeyFactory),
263  clientKeyFactory_(InitClientKeyFactory)
264 {}
265 
266 
267 const MessageFactory& sslFactory::getMessage() const
268 {
269  return messageFactory_;
270 }
271 
272 
273 const HandShakeFactory& sslFactory::getHandShake() const
274 {
275  return handShakeFactory_;
276 }
277 
278 
279 const ServerKeyFactory& sslFactory::getServerKey() const
280 {
281  return serverKeyFactory_;
282 }
283 
284 
285 const ClientKeyFactory& sslFactory::getClientKey() const
286 {
287  return clientKeyFactory_;
288 }
289 
290 
291 // extract context parameters and store
292 SSL::SSL(SSL_CTX* ctx)
293  : secure_(ctx->getMethod()->getVersion(), crypto_.use_random(),
294  ctx->getMethod()->getSide(), ctx->GetCiphers(), ctx,
295  ctx->GetDH_Parms().set_), quietShutdown_(false), has_data_(false)
296 {
297  if (int err = crypto_.get_random().GetError()) {
298  SetError(YasslError(err));
299  return;
300  }
301 
302  CertManager& cm = crypto_.use_certManager();
303  cm.CopySelfCert(ctx->getCert());
304 
305  bool serverSide = secure_.use_parms().entity_ == server_end;
306 
307  if (ctx->getKey()) {
308  if (int err = cm.SetPrivateKey(*ctx->getKey())) {
309  SetError(YasslError(err));
310  return;
311  }
312  else if (serverSide && !(ctx->GetCiphers().setSuites_)) {
313  // remove RSA or DSA suites depending on cert key type
314  ProtocolVersion pv = secure_.get_connection().version_;
315 
316  bool removeDH = secure_.use_parms().removeDH_;
317  bool removeRSA = false;
318  bool removeDSA = false;
319 
320  if (cm.get_keyType() == rsa_sa_algo)
321  removeDSA = true;
322  else
323  removeRSA = true;
324  secure_.use_parms().SetSuites(pv, removeDH, removeRSA, removeDSA);
325  }
326  }
327  else if (serverSide) {
328  SetError(no_key_file);
329  return;
330  }
331 
332  if (ctx->getMethod()->verifyPeer())
333  cm.setVerifyPeer();
334  if (ctx->getMethod()->verifyNone())
335  cm.setVerifyNone();
336  if (ctx->getMethod()->failNoCert())
337  cm.setFailNoCert();
338  cm.setVerifyCallback(ctx->getVerifyCallback());
339 
340  if (serverSide)
341  crypto_.SetDH(ctx->GetDH_Parms());
342 
343  const SSL_CTX::CertList& ca = ctx->GetCA_List();
344  SSL_CTX::CertList::const_iterator first(ca.begin());
345  SSL_CTX::CertList::const_iterator last(ca.end());
346 
347  while (first != last) {
348  if (int err = cm.CopyCaCert(*first)) {
349  SetError(YasslError(err));
350  return;
351  }
352  ++first;
353  }
354 }
355 
356 
357 // store pending security parameters from Server Hello
358 void SSL::set_pending(Cipher suite)
359 {
360  Parameters& parms = secure_.use_parms();
361 
362  switch (suite) {
363 
364  case TLS_RSA_WITH_AES_256_CBC_SHA:
365  parms.bulk_cipher_algorithm_ = aes;
366  parms.mac_algorithm_ = sha;
367  parms.kea_ = rsa_kea;
368  parms.hash_size_ = SHA_LEN;
369  parms.key_size_ = AES_256_KEY_SZ;
370  parms.iv_size_ = AES_BLOCK_SZ;
371  parms.cipher_type_ = block;
372  crypto_.setDigest(NEW_YS SHA);
373  crypto_.setCipher(NEW_YS AES(AES_256_KEY_SZ));
374  strncpy(parms.cipher_name_, cipher_names[TLS_RSA_WITH_AES_256_CBC_SHA],
375  MAX_SUITE_NAME);
376  break;
377 
378  case TLS_RSA_WITH_AES_128_CBC_SHA:
379  parms.bulk_cipher_algorithm_ = aes;
380  parms.mac_algorithm_ = sha;
381  parms.kea_ = rsa_kea;
382  parms.hash_size_ = SHA_LEN;
383  parms.key_size_ = AES_128_KEY_SZ;
384  parms.iv_size_ = AES_BLOCK_SZ;
385  parms.cipher_type_ = block;
386  crypto_.setDigest(NEW_YS SHA);
387  crypto_.setCipher(NEW_YS AES);
388  strncpy(parms.cipher_name_, cipher_names[TLS_RSA_WITH_AES_128_CBC_SHA],
389  MAX_SUITE_NAME);
390  break;
391 
392  case SSL_RSA_WITH_3DES_EDE_CBC_SHA:
393  parms.bulk_cipher_algorithm_ = triple_des;
394  parms.mac_algorithm_ = sha;
395  parms.kea_ = rsa_kea;
396  parms.hash_size_ = SHA_LEN;
397  parms.key_size_ = DES_EDE_KEY_SZ;
398  parms.iv_size_ = DES_IV_SZ;
399  parms.cipher_type_ = block;
400  crypto_.setDigest(NEW_YS SHA);
401  crypto_.setCipher(NEW_YS DES_EDE);
402  strncpy(parms.cipher_name_, cipher_names[SSL_RSA_WITH_3DES_EDE_CBC_SHA]
403  , MAX_SUITE_NAME);
404  break;
405 
406  case SSL_RSA_WITH_DES_CBC_SHA:
407  parms.bulk_cipher_algorithm_ = des;
408  parms.mac_algorithm_ = sha;
409  parms.kea_ = rsa_kea;
410  parms.hash_size_ = SHA_LEN;
411  parms.key_size_ = DES_KEY_SZ;
412  parms.iv_size_ = DES_IV_SZ;
413  parms.cipher_type_ = block;
414  crypto_.setDigest(NEW_YS SHA);
415  crypto_.setCipher(NEW_YS DES);
416  strncpy(parms.cipher_name_, cipher_names[SSL_RSA_WITH_DES_CBC_SHA],
417  MAX_SUITE_NAME);
418  break;
419 
420  case SSL_RSA_WITH_RC4_128_SHA:
421  parms.bulk_cipher_algorithm_ = rc4;
422  parms.mac_algorithm_ = sha;
423  parms.kea_ = rsa_kea;
424  parms.hash_size_ = SHA_LEN;
425  parms.key_size_ = RC4_KEY_SZ;
426  parms.iv_size_ = 0;
427  parms.cipher_type_ = stream;
428  crypto_.setDigest(NEW_YS SHA);
429  crypto_.setCipher(NEW_YS RC4);
430  strncpy(parms.cipher_name_, cipher_names[SSL_RSA_WITH_RC4_128_SHA],
431  MAX_SUITE_NAME);
432  break;
433 
434  case SSL_RSA_WITH_RC4_128_MD5:
435  parms.bulk_cipher_algorithm_ = rc4;
436  parms.mac_algorithm_ = md5;
437  parms.kea_ = rsa_kea;
438  parms.hash_size_ = MD5_LEN;
439  parms.key_size_ = RC4_KEY_SZ;
440  parms.iv_size_ = 0;
441  parms.cipher_type_ = stream;
442  crypto_.setDigest(NEW_YS MD5);
443  crypto_.setCipher(NEW_YS RC4);
444  strncpy(parms.cipher_name_, cipher_names[SSL_RSA_WITH_RC4_128_MD5],
445  MAX_SUITE_NAME);
446  break;
447 
448  case SSL_DHE_RSA_WITH_DES_CBC_SHA:
449  parms.bulk_cipher_algorithm_ = des;
450  parms.mac_algorithm_ = sha;
451  parms.kea_ = diffie_hellman_kea;
452  parms.sig_algo_ = rsa_sa_algo;
453  parms.hash_size_ = SHA_LEN;
454  parms.key_size_ = DES_KEY_SZ;
455  parms.iv_size_ = DES_IV_SZ;
456  parms.cipher_type_ = block;
457  secure_.use_connection().send_server_key_ = true; // eph
458  crypto_.setDigest(NEW_YS SHA);
459  crypto_.setCipher(NEW_YS DES);
460  strncpy(parms.cipher_name_, cipher_names[SSL_DHE_RSA_WITH_DES_CBC_SHA],
461  MAX_SUITE_NAME);
462  break;
463 
464  case SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA:
465  parms.bulk_cipher_algorithm_ = triple_des;
466  parms.mac_algorithm_ = sha;
467  parms.kea_ = diffie_hellman_kea;
468  parms.sig_algo_ = rsa_sa_algo;
469  parms.hash_size_ = SHA_LEN;
470  parms.key_size_ = DES_EDE_KEY_SZ;
471  parms.iv_size_ = DES_IV_SZ;
472  parms.cipher_type_ = block;
473  secure_.use_connection().send_server_key_ = true; // eph
474  crypto_.setDigest(NEW_YS SHA);
475  crypto_.setCipher(NEW_YS DES_EDE);
476  strncpy(parms.cipher_name_,
477  cipher_names[SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA], MAX_SUITE_NAME);
478  break;
479 
480  case TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
481  parms.bulk_cipher_algorithm_ = aes;
482  parms.mac_algorithm_ = sha;
483  parms.kea_ = diffie_hellman_kea;
484  parms.sig_algo_ = rsa_sa_algo;
485  parms.hash_size_ = SHA_LEN;
486  parms.key_size_ = AES_256_KEY_SZ;
487  parms.iv_size_ = AES_BLOCK_SZ;
488  parms.cipher_type_ = block;
489  secure_.use_connection().send_server_key_ = true; // eph
490  crypto_.setDigest(NEW_YS SHA);
491  crypto_.setCipher(NEW_YS AES(AES_256_KEY_SZ));
492  strncpy(parms.cipher_name_,
493  cipher_names[TLS_DHE_RSA_WITH_AES_256_CBC_SHA], MAX_SUITE_NAME);
494  break;
495 
496  case TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
497  parms.bulk_cipher_algorithm_ = aes;
498  parms.mac_algorithm_ = sha;
499  parms.kea_ = diffie_hellman_kea;
500  parms.sig_algo_ = rsa_sa_algo;
501  parms.hash_size_ = SHA_LEN;
502  parms.key_size_ = AES_128_KEY_SZ;
503  parms.iv_size_ = AES_BLOCK_SZ;
504  parms.cipher_type_ = block;
505  secure_.use_connection().send_server_key_ = true; // eph
506  crypto_.setDigest(NEW_YS SHA);
507  crypto_.setCipher(NEW_YS AES);
508  strncpy(parms.cipher_name_,
509  cipher_names[TLS_DHE_RSA_WITH_AES_128_CBC_SHA], MAX_SUITE_NAME);
510  break;
511 
512  case SSL_DHE_DSS_WITH_DES_CBC_SHA:
513  parms.bulk_cipher_algorithm_ = des;
514  parms.mac_algorithm_ = sha;
515  parms.kea_ = diffie_hellman_kea;
516  parms.sig_algo_ = dsa_sa_algo;
517  parms.hash_size_ = SHA_LEN;
518  parms.key_size_ = DES_KEY_SZ;
519  parms.iv_size_ = DES_IV_SZ;
520  parms.cipher_type_ = block;
521  secure_.use_connection().send_server_key_ = true; // eph
522  crypto_.setDigest(NEW_YS SHA);
523  crypto_.setCipher(NEW_YS DES);
524  strncpy(parms.cipher_name_, cipher_names[SSL_DHE_DSS_WITH_DES_CBC_SHA],
525  MAX_SUITE_NAME);
526  break;
527 
528  case SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA:
529  parms.bulk_cipher_algorithm_ = triple_des;
530  parms.mac_algorithm_ = sha;
531  parms.kea_ = diffie_hellman_kea;
532  parms.sig_algo_ = dsa_sa_algo;
533  parms.hash_size_ = SHA_LEN;
534  parms.key_size_ = DES_EDE_KEY_SZ;
535  parms.iv_size_ = DES_IV_SZ;
536  parms.cipher_type_ = block;
537  secure_.use_connection().send_server_key_ = true; // eph
538  crypto_.setDigest(NEW_YS SHA);
539  crypto_.setCipher(NEW_YS DES_EDE);
540  strncpy(parms.cipher_name_,
541  cipher_names[SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA], MAX_SUITE_NAME);
542  break;
543 
544  case TLS_DHE_DSS_WITH_AES_256_CBC_SHA:
545  parms.bulk_cipher_algorithm_ = aes;
546  parms.mac_algorithm_ = sha;
547  parms.kea_ = diffie_hellman_kea;
548  parms.sig_algo_ = dsa_sa_algo;
549  parms.hash_size_ = SHA_LEN;
550  parms.key_size_ = AES_256_KEY_SZ;
551  parms.iv_size_ = AES_BLOCK_SZ;
552  parms.cipher_type_ = block;
553  secure_.use_connection().send_server_key_ = true; // eph
554  crypto_.setDigest(NEW_YS SHA);
555  crypto_.setCipher(NEW_YS AES(AES_256_KEY_SZ));
556  strncpy(parms.cipher_name_,
557  cipher_names[TLS_DHE_DSS_WITH_AES_256_CBC_SHA], MAX_SUITE_NAME);
558  break;
559 
560  case TLS_DHE_DSS_WITH_AES_128_CBC_SHA:
561  parms.bulk_cipher_algorithm_ = aes;
562  parms.mac_algorithm_ = sha;
563  parms.kea_ = diffie_hellman_kea;
564  parms.sig_algo_ = dsa_sa_algo;
565  parms.hash_size_ = SHA_LEN;
566  parms.key_size_ = AES_128_KEY_SZ;
567  parms.iv_size_ = AES_BLOCK_SZ;
568  parms.cipher_type_ = block;
569  secure_.use_connection().send_server_key_ = true; // eph
570  crypto_.setDigest(NEW_YS SHA);
571  crypto_.setCipher(NEW_YS AES);
572  strncpy(parms.cipher_name_,
573  cipher_names[TLS_DHE_DSS_WITH_AES_128_CBC_SHA], MAX_SUITE_NAME);
574  break;
575 
576  case TLS_RSA_WITH_AES_256_CBC_RMD160:
577  parms.bulk_cipher_algorithm_ = aes;
578  parms.mac_algorithm_ = rmd;
579  parms.kea_ = rsa_kea;
580  parms.hash_size_ = RMD_LEN;
581  parms.key_size_ = AES_256_KEY_SZ;
582  parms.iv_size_ = AES_BLOCK_SZ;
583  parms.cipher_type_ = block;
584  crypto_.setDigest(NEW_YS RMD);
585  crypto_.setCipher(NEW_YS AES(AES_256_KEY_SZ));
586  strncpy(parms.cipher_name_,
587  cipher_names[TLS_RSA_WITH_AES_256_CBC_RMD160], MAX_SUITE_NAME);
588  break;
589 
590  case TLS_RSA_WITH_AES_128_CBC_RMD160:
591  parms.bulk_cipher_algorithm_ = aes;
592  parms.mac_algorithm_ = rmd;
593  parms.kea_ = rsa_kea;
594  parms.hash_size_ = RMD_LEN;
595  parms.key_size_ = AES_128_KEY_SZ;
596  parms.iv_size_ = AES_BLOCK_SZ;
597  parms.cipher_type_ = block;
598  crypto_.setDigest(NEW_YS RMD);
599  crypto_.setCipher(NEW_YS AES);
600  strncpy(parms.cipher_name_,
601  cipher_names[TLS_RSA_WITH_AES_128_CBC_RMD160], MAX_SUITE_NAME);
602  break;
603 
604  case TLS_RSA_WITH_3DES_EDE_CBC_RMD160:
605  parms.bulk_cipher_algorithm_ = triple_des;
606  parms.mac_algorithm_ = rmd;
607  parms.kea_ = rsa_kea;
608  parms.hash_size_ = RMD_LEN;
609  parms.key_size_ = DES_EDE_KEY_SZ;
610  parms.iv_size_ = DES_IV_SZ;
611  parms.cipher_type_ = block;
612  crypto_.setDigest(NEW_YS RMD);
613  crypto_.setCipher(NEW_YS DES_EDE);
614  strncpy(parms.cipher_name_,
615  cipher_names[TLS_RSA_WITH_3DES_EDE_CBC_RMD160], MAX_SUITE_NAME);
616  break;
617 
618  case TLS_DHE_RSA_WITH_3DES_EDE_CBC_RMD160:
619  parms.bulk_cipher_algorithm_ = triple_des;
620  parms.mac_algorithm_ = rmd;
621  parms.kea_ = diffie_hellman_kea;
622  parms.sig_algo_ = rsa_sa_algo;
623  parms.hash_size_ = RMD_LEN;
624  parms.key_size_ = DES_EDE_KEY_SZ;
625  parms.iv_size_ = DES_IV_SZ;
626  parms.cipher_type_ = block;
627  secure_.use_connection().send_server_key_ = true; // eph
628  crypto_.setDigest(NEW_YS RMD);
629  crypto_.setCipher(NEW_YS DES_EDE);
630  strncpy(parms.cipher_name_,
631  cipher_names[TLS_DHE_RSA_WITH_3DES_EDE_CBC_RMD160],
632  MAX_SUITE_NAME);
633  break;
634 
635  case TLS_DHE_RSA_WITH_AES_256_CBC_RMD160:
636  parms.bulk_cipher_algorithm_ = aes;
637  parms.mac_algorithm_ = rmd;
638  parms.kea_ = diffie_hellman_kea;
639  parms.sig_algo_ = rsa_sa_algo;
640  parms.hash_size_ = RMD_LEN;
641  parms.key_size_ = AES_256_KEY_SZ;
642  parms.iv_size_ = AES_BLOCK_SZ;
643  parms.cipher_type_ = block;
644  secure_.use_connection().send_server_key_ = true; // eph
645  crypto_.setDigest(NEW_YS RMD);
646  crypto_.setCipher(NEW_YS AES(AES_256_KEY_SZ));
647  strncpy(parms.cipher_name_,
648  cipher_names[TLS_DHE_RSA_WITH_AES_256_CBC_RMD160],
649  MAX_SUITE_NAME);
650  break;
651 
652  case TLS_DHE_RSA_WITH_AES_128_CBC_RMD160:
653  parms.bulk_cipher_algorithm_ = aes;
654  parms.mac_algorithm_ = rmd;
655  parms.kea_ = diffie_hellman_kea;
656  parms.sig_algo_ = rsa_sa_algo;
657  parms.hash_size_ = RMD_LEN;
658  parms.key_size_ = AES_128_KEY_SZ;
659  parms.iv_size_ = AES_BLOCK_SZ;
660  parms.cipher_type_ = block;
661  secure_.use_connection().send_server_key_ = true; // eph
662  crypto_.setDigest(NEW_YS RMD);
663  crypto_.setCipher(NEW_YS AES);
664  strncpy(parms.cipher_name_,
665  cipher_names[TLS_DHE_RSA_WITH_AES_128_CBC_RMD160],
666  MAX_SUITE_NAME);
667  break;
668 
669  case TLS_DHE_DSS_WITH_3DES_EDE_CBC_RMD160:
670  parms.bulk_cipher_algorithm_ = triple_des;
671  parms.mac_algorithm_ = rmd;
672  parms.kea_ = diffie_hellman_kea;
673  parms.sig_algo_ = dsa_sa_algo;
674  parms.hash_size_ = RMD_LEN;
675  parms.key_size_ = DES_EDE_KEY_SZ;
676  parms.iv_size_ = DES_IV_SZ;
677  parms.cipher_type_ = block;
678  secure_.use_connection().send_server_key_ = true; // eph
679  crypto_.setDigest(NEW_YS RMD);
680  crypto_.setCipher(NEW_YS DES_EDE);
681  strncpy(parms.cipher_name_,
682  cipher_names[TLS_DHE_DSS_WITH_3DES_EDE_CBC_RMD160],
683  MAX_SUITE_NAME);
684  break;
685 
686  case TLS_DHE_DSS_WITH_AES_256_CBC_RMD160:
687  parms.bulk_cipher_algorithm_ = aes;
688  parms.mac_algorithm_ = rmd;
689  parms.kea_ = diffie_hellman_kea;
690  parms.sig_algo_ = dsa_sa_algo;
691  parms.hash_size_ = RMD_LEN;
692  parms.key_size_ = AES_256_KEY_SZ;
693  parms.iv_size_ = AES_BLOCK_SZ;
694  parms.cipher_type_ = block;
695  secure_.use_connection().send_server_key_ = true; // eph
696  crypto_.setDigest(NEW_YS RMD);
697  crypto_.setCipher(NEW_YS AES(AES_256_KEY_SZ));
698  strncpy(parms.cipher_name_,
699  cipher_names[TLS_DHE_DSS_WITH_AES_256_CBC_RMD160],
700  MAX_SUITE_NAME);
701  break;
702 
703  case TLS_DHE_DSS_WITH_AES_128_CBC_RMD160:
704  parms.bulk_cipher_algorithm_ = aes;
705  parms.mac_algorithm_ = rmd;
706  parms.kea_ = diffie_hellman_kea;
707  parms.sig_algo_ = dsa_sa_algo;
708  parms.hash_size_ = RMD_LEN;
709  parms.key_size_ = AES_128_KEY_SZ;
710  parms.iv_size_ = AES_BLOCK_SZ;
711  parms.cipher_type_ = block;
712  secure_.use_connection().send_server_key_ = true; // eph
713  crypto_.setDigest(NEW_YS RMD);
714  crypto_.setCipher(NEW_YS AES);
715  strncpy(parms.cipher_name_,
716  cipher_names[TLS_DHE_DSS_WITH_AES_128_CBC_RMD160],
717  MAX_SUITE_NAME);
718  break;
719 
720  default:
721  SetError(unknown_cipher);
722  }
723 }
724 
725 #ifdef __WIN__
726 typedef volatile LONG yassl_pthread_once_t;
727 #define YASSL_PTHREAD_ONCE_INIT 0
728 #define YASSL_PTHREAD_ONCE_INPROGRESS 1
729 #define YASSL_PTHREAD_ONCE_DONE 2
730 
731 int yassl_pthread_once(yassl_pthread_once_t *once_control,
732  void (*init_routine)(void))
733 {
734  LONG state;
735 
736  /*
737  Do "dirty" read to find out if initialization is already done, to
738  save an interlocked operation in common case. Memory barriers are ensured by
739  Visual C++ volatile implementation.
740  */
741  if (*once_control == YASSL_PTHREAD_ONCE_DONE)
742  return 0;
743 
744  state= InterlockedCompareExchange(once_control, YASSL_PTHREAD_ONCE_INPROGRESS,
745  YASSL_PTHREAD_ONCE_INIT);
746 
747  switch(state)
748  {
749  case YASSL_PTHREAD_ONCE_INIT:
750  /* This is initializer thread */
751  (*init_routine)();
752  *once_control= YASSL_PTHREAD_ONCE_DONE;
753  break;
754 
755  case YASSL_PTHREAD_ONCE_INPROGRESS:
756  /* init_routine in progress. Wait for its completion */
757  while(*once_control == YASSL_PTHREAD_ONCE_INPROGRESS)
758  {
759  Sleep(1);
760  }
761  break;
762  case YASSL_PTHREAD_ONCE_DONE:
763  /* Nothing to do */
764  break;
765  }
766  return 0;
767 }
768 #else
769 #define yassl_pthread_once_t pthread_once_t
770 #if defined(PTHREAD_ONCE_INITIALIZER)
771 #define YASSL_PTHREAD_ONCE_INIT PTHREAD_ONCE_INITIALIZER
772 #else
773 #define YASSL_PTHREAD_ONCE_INIT PTHREAD_ONCE_INIT
774 #endif
775 #define yassl_pthread_once(C,F) pthread_once(C,F)
776 #endif // __WIN__
777 
778 // store peer's random
779 void SSL::set_random(const opaque* random, ConnectionEnd sender)
780 {
781  if (sender == client_end)
782  memcpy(secure_.use_connection().client_random_, random, RAN_LEN);
783  else
784  memcpy(secure_.use_connection().server_random_, random, RAN_LEN);
785 }
786 
787 
788 // store client pre master secret
789 void SSL::set_preMaster(const opaque* pre, uint sz)
790 {
791  secure_.use_connection().AllocPreSecret(sz);
792  memcpy(secure_.use_connection().pre_master_secret_, pre, sz);
793 }
794 
795 
796 // set yaSSL zlib type compression
797 int SSL::SetCompression()
798 {
799 #ifdef HAVE_LIBZ
800  secure_.use_connection().compression_ = true;
801  return 0;
802 #else
803  return -1; // not built in
804 #endif
805 }
806 
807 
808 // unset yaSSL zlib type compression
809 void SSL::UnSetCompression()
810 {
811  secure_.use_connection().compression_ = false;
812 }
813 
814 
815 // is yaSSL zlib compression on
816 bool SSL::CompressionOn() const
817 {
818  return secure_.get_connection().compression_;
819 }
820 
821 
822 // store master secret
823 void SSL::set_masterSecret(const opaque* sec)
824 {
825  memcpy(secure_.use_connection().master_secret_, sec, SECRET_LEN);
826 }
827 
828 // store server issued id
829 void SSL::set_sessionID(const opaque* sessionID)
830 {
831  memcpy(secure_.use_connection().sessionID_, sessionID, ID_LEN);
832  secure_.use_connection().sessionID_Set_ = true;
833 }
834 
835 
836 // store error
837 void SSL::SetError(YasslError ye)
838 {
839  states_.SetError(ye);
840  //strncpy(states_.useString(), e.what(), mySTL::named_exception::NAME_SIZE);
841  // TODO: add string here
842 }
843 
844 
845 // set the quiet shutdown mode (close_nofiy not sent or received on shutdown)
846 void SSL::SetQuietShutdown(bool mode)
847 {
848  quietShutdown_ = mode;
849 }
850 
851 
852 Buffers& SSL::useBuffers()
853 {
854  return buffers_;
855 }
856 
857 
858 // locals
859 namespace {
860 
861 // DeriveKeys and MasterSecret helper sets prefix letters
862 static bool setPrefix(opaque* sha_input, int i)
863 {
864  switch (i) {
865  case 0:
866  memcpy(sha_input, "A", 1);
867  break;
868  case 1:
869  memcpy(sha_input, "BB", 2);
870  break;
871  case 2:
872  memcpy(sha_input, "CCC", 3);
873  break;
874  case 3:
875  memcpy(sha_input, "DDDD", 4);
876  break;
877  case 4:
878  memcpy(sha_input, "EEEEE", 5);
879  break;
880  case 5:
881  memcpy(sha_input, "FFFFFF", 6);
882  break;
883  case 6:
884  memcpy(sha_input, "GGGGGGG", 7);
885  break;
886  default:
887  return false; // prefix_error
888  }
889  return true;
890 }
891 
892 
893 const char handshake_order[] = "Out of order HandShake Message!";
894 
895 
896 } // namespcae for locals
897 
898 
899 void SSL::order_error()
900 {
901  SetError(out_of_order);
902 }
903 
904 
905 // Create and store the master secret see page 32, 6.1
906 void SSL::makeMasterSecret()
907 {
908  if (isTLS())
909  makeTLSMasterSecret();
910  else {
911  opaque sha_output[SHA_LEN];
912 
913  const uint& preSz = secure_.get_connection().pre_secret_len_;
914  output_buffer md5_input(preSz + SHA_LEN);
915  output_buffer sha_input(PREFIX + preSz + 2 * RAN_LEN);
916 
917  MD5 md5;
918  SHA sha;
919 
920  md5_input.write(secure_.get_connection().pre_master_secret_, preSz);
921 
922  for (int i = 0; i < MASTER_ROUNDS; ++i) {
923  opaque prefix[PREFIX];
924  if (!setPrefix(prefix, i)) {
925  SetError(prefix_error);
926  return;
927  }
928 
929  sha_input.set_current(0);
930  sha_input.write(prefix, i + 1);
931 
932  sha_input.write(secure_.get_connection().pre_master_secret_,preSz);
933  sha_input.write(secure_.get_connection().client_random_, RAN_LEN);
934  sha_input.write(secure_.get_connection().server_random_, RAN_LEN);
935  sha.get_digest(sha_output, sha_input.get_buffer(),
936  sha_input.get_size());
937 
938  md5_input.set_current(preSz);
939  md5_input.write(sha_output, SHA_LEN);
940  md5.get_digest(&secure_.use_connection().master_secret_[i*MD5_LEN],
941  md5_input.get_buffer(), md5_input.get_size());
942  }
943  deriveKeys();
944  }
945  secure_.use_connection().CleanPreMaster();
946 }
947 
948 
949 // create TLSv1 master secret
950 void SSL::makeTLSMasterSecret()
951 {
952  opaque seed[SEED_LEN];
953 
954  memcpy(seed, secure_.get_connection().client_random_, RAN_LEN);
955  memcpy(&seed[RAN_LEN], secure_.get_connection().server_random_, RAN_LEN);
956 
957  PRF(secure_.use_connection().master_secret_, SECRET_LEN,
958  secure_.get_connection().pre_master_secret_,
959  secure_.get_connection().pre_secret_len_,
960  master_label, MASTER_LABEL_SZ,
961  seed, SEED_LEN);
962 
963  deriveTLSKeys();
964 }
965 
966 
967 // derive mac, write, and iv keys for server and client, see page 34, 6.2.2
968 void SSL::deriveKeys()
969 {
970  int length = 2 * secure_.get_parms().hash_size_ +
971  2 * secure_.get_parms().key_size_ +
972  2 * secure_.get_parms().iv_size_;
973  int rounds = (length + MD5_LEN - 1 ) / MD5_LEN;
974  input_buffer key_data(rounds * MD5_LEN);
975 
976  opaque sha_output[SHA_LEN];
977  opaque md5_input[SECRET_LEN + SHA_LEN];
978  opaque sha_input[KEY_PREFIX + SECRET_LEN + 2 * RAN_LEN];
979 
980  MD5 md5;
981  SHA sha;
982 
983  memcpy(md5_input, secure_.get_connection().master_secret_, SECRET_LEN);
984 
985  for (int i = 0; i < rounds; ++i) {
986  int j = i + 1;
987  if (!setPrefix(sha_input, i)) {
988  SetError(prefix_error);
989  return;
990  }
991 
992  memcpy(&sha_input[j], secure_.get_connection().master_secret_,
993  SECRET_LEN);
994  memcpy(&sha_input[j+SECRET_LEN],
995  secure_.get_connection().server_random_, RAN_LEN);
996  memcpy(&sha_input[j + SECRET_LEN + RAN_LEN],
997  secure_.get_connection().client_random_, RAN_LEN);
998  sha.get_digest(sha_output, sha_input,
999  sizeof(sha_input) - KEY_PREFIX + j);
1000 
1001  memcpy(&md5_input[SECRET_LEN], sha_output, SHA_LEN);
1002  md5.get_digest(key_data.get_buffer() + i * MD5_LEN,
1003  md5_input, sizeof(md5_input));
1004  }
1005  storeKeys(key_data.get_buffer());
1006 }
1007 
1008 
1009 // derive mac, write, and iv keys for server and client
1010 void SSL::deriveTLSKeys()
1011 {
1012  int length = 2 * secure_.get_parms().hash_size_ +
1013  2 * secure_.get_parms().key_size_ +
1014  2 * secure_.get_parms().iv_size_;
1015  opaque seed[SEED_LEN];
1016  input_buffer key_data(length);
1017 
1018  memcpy(seed, secure_.get_connection().server_random_, RAN_LEN);
1019  memcpy(&seed[RAN_LEN], secure_.get_connection().client_random_, RAN_LEN);
1020 
1021  PRF(key_data.get_buffer(), length, secure_.get_connection().master_secret_,
1022  SECRET_LEN, key_label, KEY_LABEL_SZ, seed, SEED_LEN);
1023 
1024  storeKeys(key_data.get_buffer());
1025 }
1026 
1027 
1028 // store mac, write, and iv keys for client and server
1029 void SSL::storeKeys(const opaque* key_data)
1030 {
1031  int sz = secure_.get_parms().hash_size_;
1032  memcpy(secure_.use_connection().client_write_MAC_secret_, key_data, sz);
1033  int i = sz;
1034  memcpy(secure_.use_connection().server_write_MAC_secret_,&key_data[i], sz);
1035  i += sz;
1036 
1037  sz = secure_.get_parms().key_size_;
1038  memcpy(secure_.use_connection().client_write_key_, &key_data[i], sz);
1039  i += sz;
1040  memcpy(secure_.use_connection().server_write_key_, &key_data[i], sz);
1041  i += sz;
1042 
1043  sz = secure_.get_parms().iv_size_;
1044  memcpy(secure_.use_connection().client_write_IV_, &key_data[i], sz);
1045  i += sz;
1046  memcpy(secure_.use_connection().server_write_IV_, &key_data[i], sz);
1047 
1048  setKeys();
1049 }
1050 
1051 
1052 // set encrypt/decrypt keys and ivs
1053 void SSL::setKeys()
1054 {
1055  Connection& conn = secure_.use_connection();
1056 
1057  if (secure_.get_parms().entity_ == client_end) {
1058  crypto_.use_cipher().set_encryptKey(conn.client_write_key_,
1059  conn.client_write_IV_);
1060  crypto_.use_cipher().set_decryptKey(conn.server_write_key_,
1061  conn.server_write_IV_);
1062  }
1063  else {
1064  crypto_.use_cipher().set_encryptKey(conn.server_write_key_,
1065  conn.server_write_IV_);
1066  crypto_.use_cipher().set_decryptKey(conn.client_write_key_,
1067  conn.client_write_IV_);
1068  }
1069 }
1070 
1071 
1072 
1073 // local functors
1074 namespace yassl_int_cpp_local1 { // for explicit templates
1075 
1076 struct SumData {
1077  uint total_;
1078  SumData() : total_(0) {}
1079  void operator()(input_buffer* data) { total_ += data->get_remaining(); }
1080 };
1081 
1082 
1083 struct SumBuffer {
1084  uint total_;
1085  SumBuffer() : total_(0) {}
1086  void operator()(output_buffer* buffer) { total_ += buffer->get_size(); }
1087 };
1088 
1089 } // namespace for locals
1090 using namespace yassl_int_cpp_local1;
1091 
1092 
1093 uint SSL::bufferedData()
1094 {
1095  return STL::for_each(buffers_.getData().begin(),buffers_.getData().end(),
1096  SumData()).total_;
1097 }
1098 
1099 
1100 // use input buffer to fill data
1101 void SSL::fillData(Data& data)
1102 {
1103  if (GetError()) return;
1104  uint dataSz = data.get_length(); // input, data size to fill
1105  size_t elements = buffers_.getData().size();
1106 
1107  data.set_length(0); // output, actual data filled
1108  dataSz = min(dataSz, bufferedData());
1109 
1110  for (size_t i = 0; i < elements; i++) {
1111  input_buffer* front = buffers_.getData().front();
1112  uint frontSz = front->get_remaining();
1113  uint readSz = min(dataSz - data.get_length(), frontSz);
1114 
1115  front->read(data.set_buffer() + data.get_length(), readSz);
1116  data.set_length(data.get_length() + readSz);
1117 
1118  if (readSz == frontSz) {
1119  buffers_.useData().pop_front();
1120  ysDelete(front);
1121  }
1122  if (data.get_length() == dataSz)
1123  break;
1124  }
1125 
1126  if (buffers_.getData().size() == 0) has_data_ = false; // none left
1127 }
1128 
1129 
1130 // like Fill but keep data in buffer
1131 void SSL::PeekData(Data& data)
1132 {
1133  if (GetError()) return;
1134  uint dataSz = data.get_length(); // input, data size to fill
1135  size_t elements = buffers_.getData().size();
1136 
1137  data.set_length(0); // output, actual data filled
1138  dataSz = min(dataSz, bufferedData());
1139 
1140  Buffers::inputList::iterator front = buffers_.useData().begin();
1141 
1142  while (elements) {
1143  uint frontSz = (*front)->get_remaining();
1144  uint readSz = min(dataSz - data.get_length(), frontSz);
1145  uint before = (*front)->get_current();
1146 
1147  (*front)->read(data.set_buffer() + data.get_length(), readSz);
1148  data.set_length(data.get_length() + readSz);
1149  (*front)->set_current(before);
1150 
1151  if (data.get_length() == dataSz)
1152  break;
1153 
1154  elements--;
1155  front++;
1156  }
1157 }
1158 
1159 
1160 // flush output buffer
1161 void SSL::flushBuffer()
1162 {
1163  if (GetError()) return;
1164 
1165  uint sz = STL::for_each(buffers_.getHandShake().begin(),
1166  buffers_.getHandShake().end(),
1167  SumBuffer()).total_;
1168  output_buffer out(sz);
1169  size_t elements = buffers_.getHandShake().size();
1170 
1171  for (size_t i = 0; i < elements; i++) {
1172  output_buffer* front = buffers_.getHandShake().front();
1173  out.write(front->get_buffer(), front->get_size());
1174 
1175  buffers_.useHandShake().pop_front();
1176  ysDelete(front);
1177  }
1178  Send(out.get_buffer(), out.get_size());
1179 }
1180 
1181 
1182 void SSL::Send(const byte* buffer, uint sz)
1183 {
1184  unsigned int sent = 0;
1185 
1186  if (socket_.send(buffer, sz, sent) != sz) {
1187  if (socket_.WouldBlock()) {
1188  buffers_.SetOutput(NEW_YS output_buffer(sz - sent, buffer + sent,
1189  sz - sent));
1190  SetError(YasslError(SSL_ERROR_WANT_WRITE));
1191  }
1192  else
1193  SetError(send_error);
1194  }
1195 }
1196 
1197 
1198 void SSL::SendWriteBuffered()
1199 {
1200  output_buffer* out = buffers_.TakeOutput();
1201 
1202  if (out) {
1204  Send(out->get_buffer(), out->get_size());
1205  }
1206 }
1207 
1208 
1209 // get sequence number, if verify get peer's
1210 uint SSL::get_SEQIncrement(bool verify)
1211 {
1212  if (verify)
1213  return secure_.use_connection().peer_sequence_number_++;
1214  else
1215  return secure_.use_connection().sequence_number_++;
1216 }
1217 
1218 
1219 const byte* SSL::get_macSecret(bool verify)
1220 {
1221  if ( (secure_.get_parms().entity_ == client_end && !verify) ||
1222  (secure_.get_parms().entity_ == server_end && verify) )
1223  return secure_.get_connection().client_write_MAC_secret_;
1224  else
1225  return secure_.get_connection().server_write_MAC_secret_;
1226 }
1227 
1228 
1229 void SSL::verifyState(const RecordLayerHeader& rlHeader)
1230 {
1231  if (GetError()) return;
1232 
1233  if (rlHeader.version_.major_ != 3 || rlHeader.version_.minor_ > 2) {
1234  SetError(badVersion_error);
1235  return;
1236  }
1237 
1238  if (states_.getRecord() == recordNotReady ||
1239  (rlHeader.type_ == application_data && // data and handshake
1240  states_.getHandShake() != handShakeReady) ) // isn't complete yet
1241  SetError(record_layer);
1242 }
1243 
1244 
1245 void SSL::verifyState(const HandShakeHeader& hsHeader)
1246 {
1247  if (GetError()) return;
1248 
1249  if (states_.getHandShake() == handShakeNotReady) {
1250  SetError(handshake_layer);
1251  return;
1252  }
1253 
1254  if (secure_.get_parms().entity_ == client_end)
1255  verifyClientState(hsHeader.get_handshakeType());
1256  else
1257  verifyServerState(hsHeader.get_handshakeType());
1258 }
1259 
1260 
1261 void SSL::verifyState(ClientState cs)
1262 {
1263  if (GetError()) return;
1264  if (states_.getClient() != cs) order_error();
1265 }
1266 
1267 
1268 void SSL::verifyState(ServerState ss)
1269 {
1270  if (GetError()) return;
1271  if (states_.getServer() != ss) order_error();
1272 }
1273 
1274 
1275 void SSL::verfiyHandShakeComplete()
1276 {
1277  if (GetError()) return;
1278  if (states_.getHandShake() != handShakeReady) order_error();
1279 }
1280 
1281 
1282 void SSL::verifyClientState(HandShakeType hsType)
1283 {
1284  if (GetError()) return;
1285 
1286  switch(hsType) {
1287  case server_hello :
1288  if (states_.getClient() != serverNull)
1289  order_error();
1290  break;
1291  case certificate :
1292  if (states_.getClient() != serverHelloComplete)
1293  order_error();
1294  break;
1295  case server_key_exchange :
1296  if (states_.getClient() != serverCertComplete)
1297  order_error();
1298  break;
1299  case certificate_request :
1300  if (states_.getClient() != serverCertComplete &&
1301  states_.getClient() != serverKeyExchangeComplete)
1302  order_error();
1303  break;
1304  case server_hello_done :
1305  if (states_.getClient() != serverCertComplete &&
1306  states_.getClient() != serverKeyExchangeComplete)
1307  order_error();
1308  break;
1309  case finished :
1310  if (states_.getClient() != serverHelloDoneComplete ||
1311  secure_.get_parms().pending_) // no change
1312  order_error(); // cipher yet
1313  break;
1314  default :
1315  order_error();
1316  };
1317 }
1318 
1319 
1320 void SSL::verifyServerState(HandShakeType hsType)
1321 {
1322  if (GetError()) return;
1323 
1324  switch(hsType) {
1325  case client_hello :
1326  if (states_.getServer() != clientNull)
1327  order_error();
1328  break;
1329  case certificate :
1330  if (states_.getServer() != clientHelloComplete)
1331  order_error();
1332  break;
1333  case client_key_exchange :
1334  if (states_.getServer() != clientHelloComplete)
1335  order_error();
1336  break;
1337  case certificate_verify :
1338  if (states_.getServer() != clientKeyExchangeComplete)
1339  order_error();
1340  break;
1341  case finished :
1342  if (states_.getServer() != clientKeyExchangeComplete ||
1343  secure_.get_parms().pending_) // no change
1344  order_error(); // cipher yet
1345  break;
1346  default :
1347  order_error();
1348  };
1349 }
1350 
1351 
1352 // try to find a suite match
1353 void SSL::matchSuite(const opaque* peer, uint length)
1354 {
1355  if (length == 0 || (length % 2) != 0) {
1356  SetError(bad_input);
1357  return;
1358  }
1359 
1360  // start with best, if a match we are good, Ciphers are at odd index
1361  // since all SSL and TLS ciphers have 0x00 first byte
1362  for (uint i = 1; i < secure_.get_parms().suites_size_; i += 2)
1363  for (uint j = 1; j < length; j+= 2)
1364  if (secure_.use_parms().suites_[i] == peer[j]) {
1365  secure_.use_parms().suite_[0] = 0x00;
1366  secure_.use_parms().suite_[1] = peer[j];
1367  return;
1368  }
1369 
1370  SetError(match_error);
1371 }
1372 
1373 
1374 void SSL::set_session(SSL_SESSION* s)
1375 {
1376  if (getSecurity().GetContext()->GetSessionCacheOff())
1377  return;
1378 
1379  if (s && GetSessions().lookup(s->GetID(), &secure_.use_resume())) {
1380  secure_.set_resuming(true);
1381  crypto_.use_certManager().setPeerX509(s->GetPeerX509());
1382  }
1383 }
1384 
1385 
1386 const Crypto& SSL::getCrypto() const
1387 {
1388  return crypto_;
1389 }
1390 
1391 
1392 const Security& SSL::getSecurity() const
1393 {
1394  return secure_;
1395 }
1396 
1397 
1398 const States& SSL::getStates() const
1399 {
1400  return states_;
1401 }
1402 
1403 
1404 const sslHashes& SSL::getHashes() const
1405 {
1406  return hashes_;
1407 }
1408 
1409 
1410 const sslFactory& SSL::getFactory() const
1411 {
1412  return GetSSL_Factory();
1413 }
1414 
1415 
1416 const Socket& SSL::getSocket() const
1417 {
1418  return socket_;
1419 }
1420 
1421 
1422 YasslError SSL::GetError() const
1423 {
1424  return states_.What();
1425 }
1426 
1427 
1428 bool SSL::GetQuietShutdown() const
1429 {
1430  return quietShutdown_;
1431 }
1432 
1433 
1434 bool SSL::GetMultiProtocol() const
1435 {
1436  return secure_.GetContext()->getMethod()->multipleProtocol();
1437 }
1438 
1439 
1440 Crypto& SSL::useCrypto()
1441 {
1442  return crypto_;
1443 }
1444 
1445 
1446 Security& SSL::useSecurity()
1447 {
1448  return secure_;
1449 }
1450 
1451 
1452 States& SSL::useStates()
1453 {
1454  return states_;
1455 }
1456 
1457 
1458 sslHashes& SSL::useHashes()
1459 {
1460  return hashes_;
1461 }
1462 
1463 
1464 Socket& SSL::useSocket()
1465 {
1466  return socket_;
1467 }
1468 
1469 
1470 Log& SSL::useLog()
1471 {
1472  return log_;
1473 }
1474 
1475 
1476 bool SSL::isTLS() const
1477 {
1478  return secure_.get_connection().TLS_;
1479 }
1480 
1481 
1482 bool SSL::isTLSv1_1() const
1483 {
1484  return secure_.get_connection().TLSv1_1_;
1485 }
1486 
1487 
1488 // is there buffered data available, optimization to remove iteration on buffer
1489 bool SSL::HasData() const
1490 {
1491  return has_data_;
1492 }
1493 
1494 
1495 void SSL::addData(input_buffer* data)
1496 {
1497  buffers_.useData().push_back(data);
1498  if (!has_data_) has_data_ = true;
1499 }
1500 
1501 
1502 void SSL::addBuffer(output_buffer* b)
1503 {
1504  buffers_.useHandShake().push_back(b);
1505 }
1506 
1507 
1508 void SSL_SESSION::CopyX509(X509* x)
1509 {
1510  if (x == 0) return;
1511 
1512  X509_NAME* issuer = x->GetIssuer();
1513  X509_NAME* subject = x->GetSubject();
1514  ASN1_TIME* before = x->GetBefore();
1515  ASN1_TIME* after = x->GetAfter();
1516 
1517  peerX509_ = NEW_YS X509(issuer->GetName(), issuer->GetLength(),
1518  subject->GetName(), subject->GetLength(),
1519  before, after);
1520 }
1521 
1522 
1523 // store connection parameters
1524 SSL_SESSION::SSL_SESSION(const SSL& ssl, RandomPool& ran)
1525  : timeout_(DEFAULT_TIMEOUT), random_(ran), peerX509_(0)
1526 {
1527  const Connection& conn = ssl.getSecurity().get_connection();
1528 
1529  memcpy(sessionID_, conn.sessionID_, ID_LEN);
1530  memcpy(master_secret_, conn.master_secret_, SECRET_LEN);
1531  memcpy(suite_, ssl.getSecurity().get_parms().suite_, SUITE_LEN);
1532 
1533  bornOn_ = lowResTimer();
1534 
1535  CopyX509(ssl.getCrypto().get_certManager().get_peerX509());
1536 }
1537 
1538 
1539 // for resumption copy in ssl::parameters
1540 SSL_SESSION::SSL_SESSION(RandomPool& ran)
1541  : bornOn_(0), timeout_(0), random_(ran), peerX509_(0)
1542 {
1543  memset(sessionID_, 0, ID_LEN);
1544  memset(master_secret_, 0, SECRET_LEN);
1545  memset(suite_, 0, SUITE_LEN);
1546 }
1547 
1548 
1549 SSL_SESSION& SSL_SESSION::operator=(const SSL_SESSION& that)
1550 {
1551  memcpy(sessionID_, that.sessionID_, ID_LEN);
1552  memcpy(master_secret_, that.master_secret_, SECRET_LEN);
1553  memcpy(suite_, that.suite_, SUITE_LEN);
1554 
1555  bornOn_ = that.bornOn_;
1556  timeout_ = that.timeout_;
1557 
1558  if (peerX509_) {
1559  ysDelete(peerX509_);
1560  peerX509_ = 0;
1561  }
1562  CopyX509(that.peerX509_);
1563 
1564  return *this;
1565 }
1566 
1567 
1568 const opaque* SSL_SESSION::GetID() const
1569 {
1570  return sessionID_;
1571 }
1572 
1573 
1574 const opaque* SSL_SESSION::GetSecret() const
1575 {
1576  return master_secret_;
1577 }
1578 
1579 
1580 const Cipher* SSL_SESSION::GetSuite() const
1581 {
1582  return suite_;
1583 }
1584 
1585 
1586 X509* SSL_SESSION::GetPeerX509() const
1587 {
1588  return peerX509_;
1589 }
1590 
1591 
1592 uint SSL_SESSION::GetBornOn() const
1593 {
1594  return bornOn_;
1595 }
1596 
1597 
1598 uint SSL_SESSION::GetTimeOut() const
1599 {
1600  return timeout_;
1601 }
1602 
1603 
1604 void SSL_SESSION::SetTimeOut(uint t)
1605 {
1606  timeout_ = t;
1607 }
1608 
1609 
1610 extern void clean(volatile opaque*, uint, RandomPool&);
1611 
1612 
1613 // clean up secret data
1614 SSL_SESSION::~SSL_SESSION()
1615 {
1616  volatile opaque* p = master_secret_;
1617  clean(p, SECRET_LEN, random_);
1618 
1619  ysDelete(peerX509_);
1620 }
1621 
1622 
1623 static Sessions* sessionsInstance = 0;
1624 static yassl_pthread_once_t session_created= YASSL_PTHREAD_ONCE_INIT;
1625 
1626 void Session_initialize()
1627 {
1628  sessionsInstance = NEW_YS Sessions;
1629 }
1630 
1631 extern "C"
1632 {
1633  static void c_session_initialize() { Session_initialize(); }
1634 }
1635 
1636 
1637 Sessions& GetSessions()
1638 {
1639  yassl_pthread_once(&session_created, c_session_initialize);
1640  return *sessionsInstance;
1641 }
1642 
1643 
1644 static sslFactory* sslFactoryInstance = 0;
1645 
1646 sslFactory& GetSSL_Factory()
1647 {
1648  if (!sslFactoryInstance)
1649  sslFactoryInstance = NEW_YS sslFactory;
1650  return *sslFactoryInstance;
1651 }
1652 
1653 
1654 static Errors* errorsInstance = 0;
1655 
1656 Errors& GetErrors()
1657 {
1658  if (!errorsInstance)
1659  errorsInstance = NEW_YS Errors;
1660  return *errorsInstance;
1661 }
1662 
1663 
1664 typedef Mutex::Lock Lock;
1665 
1666 
1667 
1668 void Sessions::add(const SSL& ssl)
1669 {
1670  if (ssl.getSecurity().get_connection().sessionID_Set_) {
1671  Lock guard(mutex_);
1672  list_.push_back(NEW_YS SSL_SESSION(ssl, random_));
1673  count_++;
1674  }
1675 
1676  if (count_ > SESSION_FLUSH_COUNT)
1677  if (!ssl.getSecurity().GetContext()->GetSessionCacheFlushOff())
1678  Flush();
1679 }
1680 
1681 
1682 Sessions::~Sessions()
1683 {
1684  STL::for_each(list_.begin(), list_.end(), del_ptr_zero());
1685 }
1686 
1687 
1688 // locals
1689 namespace yassl_int_cpp_local2 { // for explicit templates
1690 
1691 typedef STL::list<SSL_SESSION*>::iterator sess_iterator;
1692 typedef STL::list<ThreadError>::iterator thr_iterator;
1693 
1694 struct sess_match {
1695  const opaque* id_;
1696  explicit sess_match(const opaque* p) : id_(p) {}
1697 
1698  bool operator()(SSL_SESSION* sess)
1699  {
1700  if ( memcmp(sess->GetID(), id_, ID_LEN) == 0)
1701  return true;
1702  return false;
1703  }
1704 };
1705 
1706 
1707 THREAD_ID_T GetSelf()
1708 {
1709 #ifndef _POSIX_THREADS
1710  return GetCurrentThreadId();
1711 #else
1712  return pthread_self();
1713 #endif
1714 }
1715 
1716 struct thr_match {
1717  THREAD_ID_T id_;
1718  explicit thr_match() : id_(GetSelf()) {}
1719 
1720  bool operator()(ThreadError thr)
1721  {
1722  if (thr.threadID_ == id_)
1723  return true;
1724  return false;
1725  }
1726 };
1727 
1728 
1729 } // local namespace
1730 using namespace yassl_int_cpp_local2;
1731 
1732 
1733 // lookup session by id, return a copy if space provided
1734 SSL_SESSION* Sessions::lookup(const opaque* id, SSL_SESSION* copy)
1735 {
1736  Lock guard(mutex_);
1737  sess_iterator find = STL::find_if(list_.begin(), list_.end(),
1738  sess_match(id));
1739  if (find != list_.end()) {
1740  uint current = lowResTimer();
1741  if ( ((*find)->GetBornOn() + (*find)->GetTimeOut()) < current) {
1742  del_ptr_zero()(*find);
1743  list_.erase(find);
1744  return 0;
1745  }
1746  if (copy)
1747  *copy = *(*find);
1748  return *find;
1749  }
1750  return 0;
1751 }
1752 
1753 
1754 // remove a session by id
1755 void Sessions::remove(const opaque* id)
1756 {
1757  Lock guard(mutex_);
1758  sess_iterator find = STL::find_if(list_.begin(), list_.end(),
1759  sess_match(id));
1760  if (find != list_.end()) {
1761  del_ptr_zero()(*find);
1762  list_.erase(find);
1763  }
1764 }
1765 
1766 
1767 // flush expired sessions from cache
1768 void Sessions::Flush()
1769 {
1770  Lock guard(mutex_);
1771  sess_iterator next = list_.begin();
1772  uint current = lowResTimer();
1773 
1774  while (next != list_.end()) {
1775  sess_iterator si = next;
1776  ++next;
1777  if ( ((*si)->GetBornOn() + (*si)->GetTimeOut()) < current) {
1778  del_ptr_zero()(*si);
1779  list_.erase(si);
1780  }
1781  }
1782  count_ = 0; // reset flush counter
1783 }
1784 
1785 
1786 // remove a self thread error
1787 void Errors::Remove()
1788 {
1789  Lock guard(mutex_);
1790  thr_iterator find = STL::find_if(list_.begin(), list_.end(),
1791  thr_match());
1792  if (find != list_.end())
1793  list_.erase(find);
1794 }
1795 
1796 
1797 // lookup self error code
1798 int Errors::Lookup(bool peek)
1799 {
1800  Lock guard(mutex_);
1801  thr_iterator find = STL::find_if(list_.begin(), list_.end(),
1802  thr_match());
1803  if (find != list_.end()) {
1804  int ret = find->errorID_;
1805  if (!peek)
1806  list_.erase(find);
1807  return ret;
1808  }
1809  else
1810  return 0;
1811 }
1812 
1813 
1814 // add a new error code for self
1815 void Errors::Add(int error)
1816 {
1817  ThreadError add;
1818  add.errorID_ = error;
1819  add.threadID_ = GetSelf();
1820 
1821  Remove(); // may have old error
1822 
1823  Lock guard(mutex_);
1824  list_.push_back(add);
1825 }
1826 
1827 
1828 SSL_METHOD::SSL_METHOD(ConnectionEnd ce, ProtocolVersion pv, bool multiProto)
1829  : version_(pv), side_(ce), verifyPeer_(false), verifyNone_(false),
1830  failNoCert_(false), multipleProtocol_(multiProto)
1831 {}
1832 
1833 
1834 ProtocolVersion SSL_METHOD::getVersion() const
1835 {
1836  return version_;
1837 }
1838 
1839 
1840 ConnectionEnd SSL_METHOD::getSide() const
1841 {
1842  return side_;
1843 }
1844 
1845 
1846 void SSL_METHOD::setVerifyPeer()
1847 {
1848  verifyPeer_ = true;
1849 }
1850 
1851 
1852 void SSL_METHOD::setVerifyNone()
1853 {
1854  verifyNone_ = true;
1855 }
1856 
1857 
1858 void SSL_METHOD::setFailNoCert()
1859 {
1860  failNoCert_ = true;
1861 }
1862 
1863 
1864 bool SSL_METHOD::verifyPeer() const
1865 {
1866  return verifyPeer_;
1867 }
1868 
1869 
1870 bool SSL_METHOD::verifyNone() const
1871 {
1872  return verifyNone_;
1873 }
1874 
1875 
1876 bool SSL_METHOD::failNoCert() const
1877 {
1878  return failNoCert_;
1879 }
1880 
1881 
1882 bool SSL_METHOD::multipleProtocol() const
1883 {
1884  return multipleProtocol_;
1885 }
1886 
1887 
1889 extern "C" char *yassl_mysql_strdup(const char *from, int)
1890 {
1891  return from ? strdup(from) : NULL;
1892 }
1893 
1894 
1895 extern "C"
1896 {
1897 static int
1898 default_password_callback(char * buffer, int size_arg, int rwflag,
1899  void * /* unused: callback_data */)
1900 {
1901  char *passwd;
1902  size_t passwd_len, size= (size_t) size_arg;
1903 
1904  passwd= ::yassl_mysql_get_tty_password_ext("Enter PEM pass phrase:",
1905  yassl_mysql_strdup);
1906 
1907  if (!passwd)
1908  return 0;
1909 
1910  passwd_len= strlen(passwd);
1911 
1912  if (!passwd_len)
1913  return 0;
1914 
1915  if (size > 0)
1916  {
1917  size_t result_len= size - 1 > passwd_len ?
1918  passwd_len : size - 1;
1919  memcpy(buffer, passwd, result_len);
1920  buffer[result_len]= 0;
1921  }
1922  free(passwd);
1923  return passwd_len;
1924 }
1925 }
1926 
1927 SSL_CTX::SSL_CTX(SSL_METHOD* meth)
1928  : method_(meth), certificate_(0), privateKey_(0),
1929  passwordCb_(default_password_callback),
1930  userData_(0), sessionCacheOff_(false), sessionCacheFlushOff_(false),
1931  verifyCallback_(0)
1932 {}
1933 
1934 
1935 SSL_CTX::~SSL_CTX()
1936 {
1937  ysDelete(method_);
1938  ysDelete(certificate_);
1939  ysDelete(privateKey_);
1940 
1941  STL::for_each(caList_.begin(), caList_.end(), del_ptr_zero());
1942 }
1943 
1944 
1945 void SSL_CTX::AddCA(x509* ca)
1946 {
1947  caList_.push_back(ca);
1948 }
1949 
1950 
1951 const SSL_CTX::CertList&
1952 SSL_CTX::GetCA_List() const
1953 {
1954  return caList_;
1955 }
1956 
1957 
1958 const VerifyCallback SSL_CTX::getVerifyCallback() const
1959 {
1960  return verifyCallback_;
1961 }
1962 
1963 
1964 const x509* SSL_CTX::getCert() const
1965 {
1966  return certificate_;
1967 }
1968 
1969 
1970 const x509* SSL_CTX::getKey() const
1971 {
1972  return privateKey_;
1973 }
1974 
1975 
1976 const SSL_METHOD* SSL_CTX::getMethod() const
1977 {
1978  return method_;
1979 }
1980 
1981 
1982 const Ciphers& SSL_CTX::GetCiphers() const
1983 {
1984  return ciphers_;
1985 }
1986 
1987 
1988 const DH_Parms& SSL_CTX::GetDH_Parms() const
1989 {
1990  return dhParms_;
1991 }
1992 
1993 
1994 const Stats& SSL_CTX::GetStats() const
1995 {
1996  return stats_;
1997 }
1998 
1999 
2000 pem_password_cb SSL_CTX::GetPasswordCb() const
2001 {
2002  return passwordCb_;
2003 }
2004 
2005 
2006 void SSL_CTX::SetPasswordCb(pem_password_cb cb)
2007 {
2008  passwordCb_ = cb;
2009 }
2010 
2011 
2012 void* SSL_CTX::GetUserData() const
2013 {
2014  return userData_;
2015 }
2016 
2017 
2018 bool SSL_CTX::GetSessionCacheOff() const
2019 {
2020  return sessionCacheOff_;
2021 }
2022 
2023 
2024 bool SSL_CTX::GetSessionCacheFlushOff() const
2025 {
2026  return sessionCacheFlushOff_;
2027 }
2028 
2029 
2030 void SSL_CTX::SetUserData(void* data)
2031 {
2032  userData_ = data;
2033 }
2034 
2035 
2036 void SSL_CTX::SetSessionCacheOff()
2037 {
2038  sessionCacheOff_ = true;
2039 }
2040 
2041 
2042 void SSL_CTX::SetSessionCacheFlushOff()
2043 {
2044  sessionCacheFlushOff_ = true;
2045 }
2046 
2047 
2048 void SSL_CTX::setVerifyPeer()
2049 {
2050  method_->setVerifyPeer();
2051 }
2052 
2053 
2054 void SSL_CTX::setVerifyNone()
2055 {
2056  method_->setVerifyNone();
2057 }
2058 
2059 
2060 void SSL_CTX::setFailNoCert()
2061 {
2062  method_->setFailNoCert();
2063 }
2064 
2065 
2066 void SSL_CTX::setVerifyCallback(VerifyCallback vc)
2067 {
2068  verifyCallback_ = vc;
2069 }
2070 
2071 
2072 bool SSL_CTX::SetDH(const DH& dh)
2073 {
2074  dhParms_.p_ = dh.p->int_;
2075  dhParms_.g_ = dh.g->int_;
2076 
2077  return dhParms_.set_ = true;
2078 }
2079 
2080 
2081 bool SSL_CTX::SetCipherList(const char* list)
2082 {
2083  if (!list)
2084  return false;
2085 
2086  bool ret = false;
2087  char name[MAX_SUITE_NAME];
2088 
2089  char needle[] = ":";
2090  char* haystack = const_cast<char*>(list);
2091  char* prev;
2092 
2093  const int suiteSz = sizeof(cipher_names) / sizeof(cipher_names[0]);
2094  int idx = 0;
2095 
2096  for(;;) {
2097  size_t len;
2098  prev = haystack;
2099  haystack = strstr(haystack, needle);
2100 
2101  if (!haystack) // last cipher
2102  len = min(sizeof(name), strlen(prev));
2103  else
2104  len = min(sizeof(name), (size_t)(haystack - prev));
2105 
2106  strncpy(name, prev, len);
2107  name[(len == sizeof(name)) ? len - 1 : len] = 0;
2108 
2109  for (int i = 0; i < suiteSz; i++)
2110  if (strncmp(name, cipher_names[i], sizeof(name)) == 0) {
2111 
2112  ciphers_.suites_[idx++] = 0x00; // first byte always zero
2113  ciphers_.suites_[idx++] = i;
2114 
2115  if (!ret) ret = true; // found at least one
2116  break;
2117  }
2118  if (!haystack) break;
2119  haystack++;
2120  }
2121 
2122  if (ret) {
2123  ciphers_.setSuites_ = true;
2124  ciphers_.suiteSz_ = idx;
2125  }
2126 
2127  return ret;
2128 }
2129 
2130 
2131 void SSL_CTX::IncrementStats(StatsField fd)
2132 {
2133 
2134  Lock guard(mutex_);
2135 
2136  switch (fd) {
2137 
2138  case Accept:
2139  ++stats_.accept_;
2140  break;
2141 
2142  case Connect:
2143  ++stats_.connect_;
2144  break;
2145 
2146  case AcceptGood:
2147  ++stats_.acceptGood_;
2148  break;
2149 
2150  case ConnectGood:
2151  ++stats_.connectGood_;
2152  break;
2153 
2154  case AcceptRenegotiate:
2155  ++stats_.acceptRenegotiate_;
2156  break;
2157 
2158  case ConnectRenegotiate:
2159  ++stats_.connectRenegotiate_;
2160  break;
2161 
2162  case Hits:
2163  ++stats_.hits_;
2164  break;
2165 
2166  case CbHits:
2167  ++stats_.cbHits_;
2168  break;
2169 
2170  case CacheFull:
2171  ++stats_.cacheFull_;
2172  break;
2173 
2174  case Misses:
2175  ++stats_.misses_;
2176  break;
2177 
2178  case Timeouts:
2179  ++stats_.timeouts_;
2180  break;
2181 
2182  case Number:
2183  ++stats_.number_;
2184  break;
2185 
2186  case GetCacheSize:
2187  ++stats_.getCacheSize_;
2188  break;
2189 
2190  case VerifyMode:
2191  ++stats_.verifyMode_;
2192  break;
2193 
2194  case VerifyDepth:
2195  ++stats_.verifyDepth_;
2196  break;
2197 
2198  default:
2199  break;
2200  }
2201 }
2202 
2203 
2204 Crypto::Crypto()
2205  : digest_(0), cipher_(0), dh_(0)
2206 {}
2207 
2208 
2209 Crypto::~Crypto()
2210 {
2211  ysDelete(dh_);
2212  ysDelete(cipher_);
2213  ysDelete(digest_);
2214 }
2215 
2216 
2217 const Digest& Crypto::get_digest() const
2218 {
2219  return *digest_;
2220 }
2221 
2222 
2223 const BulkCipher& Crypto::get_cipher() const
2224 {
2225  return *cipher_;
2226 }
2227 
2228 
2229 const DiffieHellman& Crypto::get_dh() const
2230 {
2231  return *dh_;
2232 }
2233 
2234 
2235 const RandomPool& Crypto::get_random() const
2236 {
2237  return random_;
2238 }
2239 
2240 
2241 const CertManager& Crypto::get_certManager() const
2242 {
2243  return cert_;
2244 }
2245 
2246 
2247 
2248 Digest& Crypto::use_digest()
2249 {
2250  return *digest_;
2251 }
2252 
2253 
2254 BulkCipher& Crypto::use_cipher()
2255 {
2256  return *cipher_;
2257 }
2258 
2259 
2260 DiffieHellman& Crypto::use_dh()
2261 {
2262  return *dh_;
2263 }
2264 
2265 
2266 RandomPool& Crypto::use_random()
2267 {
2268  return random_;
2269 }
2270 
2271 
2272 CertManager& Crypto::use_certManager()
2273 {
2274  return cert_;
2275 }
2276 
2277 
2278 
2279 void Crypto::SetDH(DiffieHellman* dh)
2280 {
2281  dh_ = dh;
2282 }
2283 
2284 
2285 void Crypto::SetDH(const DH_Parms& dh)
2286 {
2287  if (dh.set_)
2288  dh_ = NEW_YS DiffieHellman(dh.p_, dh.g_, random_);
2289 }
2290 
2291 
2292 bool Crypto::DhSet()
2293 {
2294  return dh_ != 0;
2295 }
2296 
2297 
2298 void Crypto::setDigest(Digest* digest)
2299 {
2300  digest_ = digest;
2301 }
2302 
2303 
2304 void Crypto::setCipher(BulkCipher* c)
2305 {
2306  cipher_ = c;
2307 }
2308 
2309 
2310 const MD5& sslHashes::get_MD5() const
2311 {
2312  return md5HandShake_;
2313 }
2314 
2315 
2316 const SHA& sslHashes::get_SHA() const
2317 {
2318  return shaHandShake_;
2319 }
2320 
2321 
2322 const Finished& sslHashes::get_verify() const
2323 {
2324  return verify_;
2325 }
2326 
2327 
2328 const Hashes& sslHashes::get_certVerify() const
2329 {
2330  return certVerify_;
2331 }
2332 
2333 
2334 MD5& sslHashes::use_MD5(){
2335  return md5HandShake_;
2336 }
2337 
2338 
2339 SHA& sslHashes::use_SHA()
2340 {
2341  return shaHandShake_;
2342 }
2343 
2344 
2345 Finished& sslHashes::use_verify()
2346 {
2347  return verify_;
2348 }
2349 
2350 
2351 Hashes& sslHashes::use_certVerify()
2352 {
2353  return certVerify_;
2354 }
2355 
2356 
2357 Buffers::Buffers() : prevSent(0), plainSz(0), rawInput_(0), output_(0)
2358 {}
2359 
2360 
2361 Buffers::~Buffers()
2362 {
2363  STL::for_each(handShakeList_.begin(), handShakeList_.end(),
2364  del_ptr_zero()) ;
2365  STL::for_each(dataList_.begin(), dataList_.end(),
2366  del_ptr_zero()) ;
2367  ysDelete(rawInput_);
2368  ysDelete(output_);
2369 }
2370 
2371 
2372 void Buffers::SetOutput(output_buffer* ob)
2373 {
2374  output_ = ob;
2375 }
2376 
2377 
2378 void Buffers::SetRawInput(input_buffer* ib)
2379 {
2380  rawInput_ = ib;
2381 }
2382 
2383 
2384 input_buffer* Buffers::TakeRawInput()
2385 {
2386  input_buffer* ret = rawInput_;
2387  rawInput_ = 0;
2388 
2389  return ret;
2390 }
2391 
2392 
2393 output_buffer* Buffers::TakeOutput()
2394 {
2395  output_buffer* ret = output_;
2396  output_ = 0;
2397 
2398  return ret;
2399 }
2400 
2401 
2402 const Buffers::inputList& Buffers::getData() const
2403 {
2404  return dataList_;
2405 }
2406 
2407 
2408 const Buffers::outputList& Buffers::getHandShake() const
2409 {
2410  return handShakeList_;
2411 }
2412 
2413 
2414 Buffers::inputList& Buffers::useData()
2415 {
2416  return dataList_;
2417 }
2418 
2419 
2420 Buffers::outputList& Buffers::useHandShake()
2421 {
2422  return handShakeList_;
2423 }
2424 
2425 
2426 Security::Security(ProtocolVersion pv, RandomPool& ran, ConnectionEnd ce,
2427  const Ciphers& ciphers, SSL_CTX* ctx, bool haveDH)
2428  : conn_(pv, ran), parms_(ce, ciphers, pv, haveDH), resumeSession_(ran),
2429  ctx_(ctx), resuming_(false)
2430 {}
2431 
2432 
2433 const Connection& Security::get_connection() const
2434 {
2435  return conn_;
2436 }
2437 
2438 
2439 const SSL_CTX* Security::GetContext() const
2440 {
2441  return ctx_;
2442 }
2443 
2444 
2445 const Parameters& Security::get_parms() const
2446 {
2447  return parms_;
2448 }
2449 
2450 
2451 const SSL_SESSION& Security::get_resume() const
2452 {
2453  return resumeSession_;
2454 }
2455 
2456 
2457 bool Security::get_resuming() const
2458 {
2459  return resuming_;
2460 }
2461 
2462 
2463 Connection& Security::use_connection()
2464 {
2465  return conn_;
2466 }
2467 
2468 
2469 Parameters& Security::use_parms()
2470 {
2471  return parms_;
2472 }
2473 
2474 
2475 SSL_SESSION& Security::use_resume()
2476 {
2477  return resumeSession_;
2478 }
2479 
2480 
2481 void Security::set_resuming(bool b)
2482 {
2483  resuming_ = b;
2484 }
2485 
2486 
2487 X509_NAME::X509_NAME(const char* n, size_t sz)
2488  : name_(0), sz_(sz)
2489 {
2490  if (sz) {
2491  name_ = NEW_YS char[sz];
2492  memcpy(name_, n, sz);
2493  }
2494  entry_.data = 0;
2495 }
2496 
2497 
2498 X509_NAME::~X509_NAME()
2499 {
2500  ysArrayDelete(name_);
2501  ysArrayDelete(entry_.data);
2502 }
2503 
2504 
2505 const char* X509_NAME::GetName() const
2506 {
2507  return name_;
2508 }
2509 
2510 
2511 size_t X509_NAME::GetLength() const
2512 {
2513  return sz_;
2514 }
2515 
2516 
2517 X509::X509(const char* i, size_t iSz, const char* s, size_t sSz,
2518  ASN1_STRING *b, ASN1_STRING *a)
2519  : issuer_(i, iSz), subject_(s, sSz),
2520  beforeDate_((char *) b->data, b->length, b->type),
2521  afterDate_((char *) a->data, a->length, a->type)
2522 {}
2523 
2524 
2525 X509_NAME* X509::GetIssuer()
2526 {
2527  return &issuer_;
2528 }
2529 
2530 
2531 X509_NAME* X509::GetSubject()
2532 {
2533  return &subject_;
2534 }
2535 
2536 
2537 ASN1_TIME* X509::GetBefore()
2538 {
2539  return beforeDate_.GetString();
2540 }
2541 
2542 
2543 ASN1_TIME* X509::GetAfter()
2544 {
2545  return afterDate_.GetString();
2546 }
2547 
2548 
2549 ASN1_STRING* X509_NAME::GetEntry(int i)
2550 {
2551  if (i < 0 || i >= int(sz_))
2552  return 0;
2553 
2554  if (entry_.data)
2555  ysArrayDelete(entry_.data);
2556  entry_.data = NEW_YS byte[sz_]; // max size;
2557 
2558  memcpy(entry_.data, &name_[i], sz_ - i);
2559  if (entry_.data[sz_ -i - 1]) {
2560  entry_.data[sz_ - i] = 0;
2561  entry_.length = int(sz_) - i;
2562  }
2563  else
2564  entry_.length = int(sz_) - i - 1;
2565  entry_.type = 0;
2566 
2567  return &entry_;
2568 }
2569 
2570 
2571 StringHolder::StringHolder(const char* str, int sz, byte type)
2572 {
2573  asnString_.length = sz;
2574  asnString_.data = NEW_YS byte[sz + 1];
2575  memcpy(asnString_.data, str, sz);
2576  asnString_.type = type;
2577 }
2578 
2579 
2580 StringHolder::~StringHolder()
2581 {
2582  ysArrayDelete(asnString_.data);
2583 }
2584 
2585 
2586 ASN1_STRING* StringHolder::GetString()
2587 {
2588  return &asnString_;
2589 }
2590 
2591 
2592 #ifdef HAVE_LIBZ
2593 
2594  void* myAlloc(void* /* opaque */, unsigned int item, unsigned int size)
2595  {
2596  return NEW_YS unsigned char[item * size];
2597  }
2598 
2599 
2600  void myFree(void* /* opaque */, void* memory)
2601  {
2602  unsigned char* ptr = static_cast<unsigned char*>(memory);
2603  yaSSL::ysArrayDelete(ptr);
2604  }
2605 
2606 
2607  // put size in front of compressed data
2608  int Compress(const byte* in, int sz, input_buffer& buffer)
2609  {
2610  byte tmp[LENGTH_SZ];
2611  z_stream c_stream; /* compression stream */
2612 
2613  buffer.allocate(sz + sizeof(uint16) + COMPRESS_EXTRA);
2614 
2615  c_stream.zalloc = myAlloc;
2616  c_stream.zfree = myFree;
2617  c_stream.opaque = (voidpf)0;
2618 
2619  c_stream.next_in = const_cast<byte*>(in);
2620  c_stream.avail_in = sz;
2621  c_stream.next_out = buffer.get_buffer() + sizeof(tmp);
2622  c_stream.avail_out = buffer.get_capacity() - sizeof(tmp);
2623 
2624  if (deflateInit(&c_stream, 8) != Z_OK) return -1;
2625  int err = deflate(&c_stream, Z_FINISH);
2626  deflateEnd(&c_stream);
2627  if (err != Z_OK && err != Z_STREAM_END) return -1;
2628 
2629  c16toa(sz, tmp);
2630  memcpy(buffer.get_buffer(), tmp, sizeof(tmp));
2631  buffer.add_size(c_stream.total_out + sizeof(tmp));
2632 
2633  return 0;
2634  }
2635 
2636 
2637  // get uncompressed size in front
2638  int DeCompress(input_buffer& in, int sz, input_buffer& out)
2639  {
2640  byte tmp[LENGTH_SZ];
2641 
2642  in.read(tmp, sizeof(tmp));
2643 
2644  uint16 len;
2645  ato16(tmp, len);
2646 
2647  out.allocate(len);
2648 
2649  z_stream d_stream; /* decompression stream */
2650 
2651  d_stream.zalloc = myAlloc;
2652  d_stream.zfree = myFree;
2653  d_stream.opaque = (voidpf)0;
2654 
2655  d_stream.next_in = in.get_buffer() + in.get_current();
2656  d_stream.avail_in = sz - sizeof(tmp);
2657  d_stream.next_out = out.get_buffer();
2658  d_stream.avail_out = out.get_capacity();
2659 
2660  if (inflateInit(&d_stream) != Z_OK) return -1;
2661  int err = inflate(&d_stream, Z_FINISH);
2662  inflateEnd(&d_stream);
2663  if (err != Z_OK && err != Z_STREAM_END) return -1;
2664 
2665  out.add_size(d_stream.total_out);
2666  in.set_current(in.get_current() + sz - sizeof(tmp));
2667 
2668  return 0;
2669  }
2670 
2671 
2672 #else // LIBZ
2673 
2674  // these versions should never get called
2675  int Compress(const byte* in, int sz, input_buffer& buffer)
2676  {
2677  return -1;
2678  }
2679 
2680 
2681  int DeCompress(input_buffer& in, int sz, input_buffer& out)
2682  {
2683  return -1;
2684  }
2685 
2686 
2687 #endif // LIBZ
2688 
2689 
2690 } // namespace
2691 
2692 
2693 
2694 extern "C" void yaSSL_CleanUp()
2695 {
2696  TaoCrypt::CleanUp();
2697  yaSSL::ysDelete(yaSSL::sslFactoryInstance);
2698  yaSSL::ysDelete(yaSSL::sessionsInstance);
2699  yaSSL::ysDelete(yaSSL::errorsInstance);
2700 
2701  // In case user calls more than once, prevent seg fault
2702  yaSSL::sslFactoryInstance = 0;
2703  yaSSL::sessionsInstance = 0;
2704  yaSSL::errorsInstance = 0;
2705 }
2706 
2707 
2708 #ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
2709 namespace mySTL {
2710 template yaSSL::yassl_int_cpp_local1::SumData for_each<mySTL::list<yaSSL::input_buffer*>::iterator, yaSSL::yassl_int_cpp_local1::SumData>(mySTL::list<yaSSL::input_buffer*>::iterator, mySTL::list<yaSSL::input_buffer*>::iterator, yaSSL::yassl_int_cpp_local1::SumData);
2714 }
2715 #endif
2716