~ubuntu-branches/debian/experimental/kopete/experimental

« back to all changes in this revision

Viewing changes to protocols/jabber/googletalk/libjingle/talk/base/opensslstreamadapter.cc

  • Committer: Package Import Robot
  • Author(s): Maximiliano Curia
  • Date: 2015-02-24 11:32:57 UTC
  • mfrom: (1.1.41 vivid)
  • Revision ID: package-import@ubuntu.com-20150224113257-gnupg4v7lzz18ij0
Tags: 4:14.12.2-1
* New upstream release (14.12.2).
* Bump Standards-Version to 3.9.6, no changes needed.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/*
2
 
 * libjingle
3
 
 * Copyright 2004--2008, Google Inc.
4
 
 *
5
 
 * Redistribution and use in source and binary forms, with or without
6
 
 * modification, are permitted provided that the following conditions are met:
7
 
 *
8
 
 *  1. Redistributions of source code must retain the above copyright notice,
9
 
 *     this list of conditions and the following disclaimer.
10
 
 *  2. Redistributions in binary form must reproduce the above copyright notice,
11
 
 *     this list of conditions and the following disclaimer in the documentation
12
 
 *     and/or other materials provided with the distribution.
13
 
 *  3. The name of the author may not be used to endorse or promote products
14
 
 *     derived from this software without specific prior written permission.
15
 
 *
16
 
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17
 
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18
 
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19
 
 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20
 
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21
 
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22
 
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23
 
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24
 
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25
 
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26
 
 */
27
 
 
28
 
#if HAVE_CONFIG_H
29
 
#include "config.h"
30
 
#endif  // HAVE_CONFIG_H
31
 
 
32
 
#if HAVE_OPENSSL_SSL_H
33
 
 
34
 
#include "talk/base/opensslstreamadapter.h"
35
 
 
36
 
#include <openssl/bio.h>
37
 
#include <openssl/crypto.h>
38
 
#include <openssl/err.h>
39
 
#include <openssl/rand.h>
40
 
#include <openssl/ssl.h>
41
 
#include <openssl/x509v3.h>
42
 
 
43
 
#include <vector>
44
 
 
45
 
#include "talk/base/common.h"
46
 
#include "talk/base/logging.h"
47
 
#include "talk/base/stream.h"
48
 
#include "talk/base/openssladapter.h"
49
 
#include "talk/base/openssldigest.h"
50
 
#include "talk/base/opensslidentity.h"
51
 
#include "talk/base/stringutils.h"
52
 
#include "talk/base/thread.h"
53
 
 
54
 
namespace talk_base {
55
 
 
56
 
#if (OPENSSL_VERSION_NUMBER >= 0x10001000L)
57
 
#define HAVE_DTLS_SRTP
58
 
#endif
59
 
 
60
 
#if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
61
 
#define HAVE_DTLS
62
 
#endif
63
 
 
64
 
#ifdef HAVE_DTLS_SRTP
65
 
// SRTP cipher suite table
66
 
struct SrtpCipherMapEntry {
67
 
  const char* external_name;
68
 
  const char* internal_name;
69
 
};
70
 
 
71
 
// This isn't elegant, but it's better than an external reference
72
 
static SrtpCipherMapEntry SrtpCipherMap[] = {
73
 
  {"AES_CM_128_HMAC_SHA1_80", "SRTP_AES128_CM_SHA1_80"},
74
 
  {"AES_CM_128_HMAC_SHA1_32", "SRTP_AES128_CM_SHA1_32"},
75
 
  {NULL, NULL}
76
 
};
77
 
#endif
78
 
 
79
 
//////////////////////////////////////////////////////////////////////
80
 
// StreamBIO
81
 
//////////////////////////////////////////////////////////////////////
82
 
 
83
 
static int stream_write(BIO* h, const char* buf, int num);
84
 
static int stream_read(BIO* h, char* buf, int size);
85
 
static int stream_puts(BIO* h, const char* str);
86
 
static long stream_ctrl(BIO* h, int cmd, long arg1, void* arg2);
87
 
static int stream_new(BIO* h);
88
 
static int stream_free(BIO* data);
89
 
 
90
 
static BIO_METHOD methods_stream = {
91
 
  BIO_TYPE_BIO,
92
 
  "stream",
93
 
  stream_write,
94
 
  stream_read,
95
 
  stream_puts,
96
 
  0,
97
 
  stream_ctrl,
98
 
  stream_new,
99
 
  stream_free,
100
 
  NULL,
101
 
};
102
 
 
103
 
static BIO_METHOD* BIO_s_stream() { return(&methods_stream); }
104
 
 
105
 
static BIO* BIO_new_stream(StreamInterface* stream) {
106
 
  BIO* ret = BIO_new(BIO_s_stream());
107
 
  if (ret == NULL)
108
 
    return NULL;
109
 
  ret->ptr = stream;
110
 
  return ret;
111
 
}
112
 
 
113
 
// bio methods return 1 (or at least non-zero) on success and 0 on failure.
114
 
 
115
 
static int stream_new(BIO* b) {
116
 
  b->shutdown = 0;
117
 
  b->init = 1;
118
 
  b->num = 0;  // 1 means end-of-stream
119
 
  b->ptr = 0;
120
 
  return 1;
121
 
}
122
 
 
123
 
static int stream_free(BIO* b) {
124
 
  if (b == NULL)
125
 
    return 0;
126
 
  return 1;
127
 
}
128
 
 
129
 
static int stream_read(BIO* b, char* out, int outl) {
130
 
  if (!out)
131
 
    return -1;
132
 
  StreamInterface* stream = static_cast<StreamInterface*>(b->ptr);
133
 
  BIO_clear_retry_flags(b);
134
 
  size_t read;
135
 
  int error;
136
 
  StreamResult result = stream->Read(out, outl, &read, &error);
137
 
  if (result == SR_SUCCESS) {
138
 
    return read;
139
 
  } else if (result == SR_EOS) {
140
 
    b->num = 1;
141
 
  } else if (result == SR_BLOCK) {
142
 
    BIO_set_retry_read(b);
143
 
  }
144
 
  return -1;
145
 
}
146
 
 
147
 
static int stream_write(BIO* b, const char* in, int inl) {
148
 
  if (!in)
149
 
    return -1;
150
 
  StreamInterface* stream = static_cast<StreamInterface*>(b->ptr);
151
 
  BIO_clear_retry_flags(b);
152
 
  size_t written;
153
 
  int error;
154
 
  StreamResult result = stream->Write(in, inl, &written, &error);
155
 
  if (result == SR_SUCCESS) {
156
 
    return written;
157
 
  } else if (result == SR_BLOCK) {
158
 
    BIO_set_retry_write(b);
159
 
  }
160
 
  return -1;
161
 
}
162
 
 
163
 
static int stream_puts(BIO* b, const char* str) {
164
 
  return stream_write(b, str, strlen(str));
165
 
}
166
 
 
167
 
static long stream_ctrl(BIO* b, int cmd, long num, void* ptr) {
168
 
  UNUSED(num);
169
 
  UNUSED(ptr);
170
 
 
171
 
  switch (cmd) {
172
 
    case BIO_CTRL_RESET:
173
 
      return 0;
174
 
    case BIO_CTRL_EOF:
175
 
      return b->num;
176
 
    case BIO_CTRL_WPENDING:
177
 
    case BIO_CTRL_PENDING:
178
 
      return 0;
179
 
    case BIO_CTRL_FLUSH:
180
 
      return 1;
181
 
    default:
182
 
      return 0;
183
 
  }
184
 
}
185
 
 
186
 
/////////////////////////////////////////////////////////////////////////////
187
 
// OpenSSLStreamAdapter
188
 
/////////////////////////////////////////////////////////////////////////////
189
 
 
190
 
OpenSSLStreamAdapter::OpenSSLStreamAdapter(StreamInterface* stream)
191
 
    : SSLStreamAdapter(stream),
192
 
      state_(SSL_NONE),
193
 
      role_(SSL_CLIENT),
194
 
      ssl_read_needs_write_(false), ssl_write_needs_read_(false),
195
 
      ssl_(NULL), ssl_ctx_(NULL),
196
 
      custom_verification_succeeded_(false),
197
 
      ssl_mode_(SSL_MODE_TLS) {
198
 
}
199
 
 
200
 
OpenSSLStreamAdapter::~OpenSSLStreamAdapter() {
201
 
  Cleanup();
202
 
}
203
 
 
204
 
void OpenSSLStreamAdapter::SetIdentity(SSLIdentity* identity) {
205
 
  ASSERT(identity_.get() == NULL);
206
 
  identity_.reset(static_cast<OpenSSLIdentity*>(identity));
207
 
}
208
 
 
209
 
void OpenSSLStreamAdapter::SetServerRole(SSLRole role) {
210
 
  role_ = role;
211
 
}
212
 
 
213
 
void OpenSSLStreamAdapter::SetPeerCertificate(SSLCertificate* cert) {
214
 
  ASSERT(peer_certificate_.get() == NULL);
215
 
  ASSERT(peer_certificate_digest_algorithm_.empty());
216
 
  ASSERT(ssl_server_name_.empty());
217
 
  peer_certificate_.reset(static_cast<OpenSSLCertificate*>(cert));
218
 
}
219
 
 
220
 
bool OpenSSLStreamAdapter::SetPeerCertificateDigest(const std::string
221
 
                                                    &digest_alg,
222
 
                                                    const unsigned char*
223
 
                                                    digest_val,
224
 
                                                    size_t digest_len) {
225
 
  ASSERT(peer_certificate_.get() == NULL);
226
 
  ASSERT(peer_certificate_digest_algorithm_.size() == 0);
227
 
  ASSERT(ssl_server_name_.empty());
228
 
  size_t expected_len;
229
 
 
230
 
  if (!OpenSSLDigest::GetDigestSize(digest_alg, &expected_len)) {
231
 
    LOG(LS_WARNING) << "Unknown digest algorithm: " << digest_alg;
232
 
    return false;
233
 
  }
234
 
  if (expected_len != digest_len)
235
 
    return false;
236
 
 
237
 
  peer_certificate_digest_value_.SetData(digest_val, digest_len);
238
 
  peer_certificate_digest_algorithm_ = digest_alg;
239
 
 
240
 
  return true;
241
 
}
242
 
 
243
 
// Key Extractor interface
244
 
bool OpenSSLStreamAdapter::ExportKeyingMaterial(const std::string& label,
245
 
                                                const uint8* context,
246
 
                                                size_t context_len,
247
 
                                                bool use_context,
248
 
                                                uint8* result,
249
 
                                                size_t result_len) {
250
 
#ifdef HAVE_DTLS_SRTP
251
 
  int i;
252
 
 
253
 
  i = SSL_export_keying_material(ssl_, result, result_len,
254
 
                                 label.c_str(), label.length(),
255
 
                                 const_cast<uint8 *>(context),
256
 
                                 context_len, use_context);
257
 
 
258
 
  if (i != 1)
259
 
    return false;
260
 
 
261
 
  return true;
262
 
#else
263
 
  return false;
264
 
#endif
265
 
}
266
 
 
267
 
bool OpenSSLStreamAdapter::SetDtlsSrtpCiphers(
268
 
    const std::vector<std::string>& ciphers) {
269
 
  std::string internal_ciphers;
270
 
 
271
 
  if (state_ != SSL_NONE)
272
 
    return false;
273
 
 
274
 
#ifdef HAVE_DTLS_SRTP
275
 
  for (std::vector<std::string>::const_iterator cipher = ciphers.begin();
276
 
       cipher != ciphers.end(); ++cipher) {
277
 
    bool found = false;
278
 
    for (SrtpCipherMapEntry *entry = SrtpCipherMap; entry->internal_name;
279
 
         ++entry) {
280
 
      if (*cipher == entry->external_name) {
281
 
        found = true;
282
 
        if (!internal_ciphers.empty())
283
 
          internal_ciphers += ":";
284
 
        internal_ciphers += entry->internal_name;
285
 
        break;
286
 
      }
287
 
    }
288
 
 
289
 
    if (!found) {
290
 
      LOG(LS_ERROR) << "Could not find cipher: " << *cipher;
291
 
      return false;
292
 
    }
293
 
  }
294
 
 
295
 
  if (internal_ciphers.empty())
296
 
    return false;
297
 
 
298
 
  srtp_ciphers_ = internal_ciphers;
299
 
  return true;
300
 
#else
301
 
  return false;
302
 
#endif
303
 
}
304
 
 
305
 
bool OpenSSLStreamAdapter::GetDtlsSrtpCipher(std::string* cipher) {
306
 
#ifdef HAVE_DTLS_SRTP
307
 
  ASSERT(state_ == SSL_CONNECTED);
308
 
  if (state_ != SSL_CONNECTED)
309
 
    return false;
310
 
 
311
 
  SRTP_PROTECTION_PROFILE *srtp_profile =
312
 
      SSL_get_selected_srtp_profile(ssl_);
313
 
 
314
 
  if (!srtp_profile)
315
 
    return NULL;
316
 
 
317
 
  for (SrtpCipherMapEntry *entry = SrtpCipherMap;
318
 
       entry->internal_name; ++entry) {
319
 
    if (!strcmp(entry->internal_name, srtp_profile->name)) {
320
 
      *cipher = entry->external_name;
321
 
      return true;
322
 
    }
323
 
  }
324
 
 
325
 
  ASSERT(false);  // This should never happen
326
 
 
327
 
  return false;
328
 
#else
329
 
  return false;
330
 
#endif
331
 
}
332
 
 
333
 
int OpenSSLStreamAdapter::StartSSLWithServer(const char* server_name) {
334
 
  ASSERT(server_name != NULL && server_name[0] != '\0');
335
 
  ssl_server_name_ = server_name;
336
 
  return StartSSL();
337
 
}
338
 
 
339
 
int OpenSSLStreamAdapter::StartSSLWithPeer() {
340
 
  ASSERT(ssl_server_name_.empty());
341
 
  // It is permitted to specify peer_certificate_ only later.
342
 
  return StartSSL();
343
 
}
344
 
 
345
 
void OpenSSLStreamAdapter::SetMode(SSLMode mode) {
346
 
  ASSERT(state_ == SSL_NONE);
347
 
  ssl_mode_ = mode;
348
 
}
349
 
 
350
 
//
351
 
// StreamInterface Implementation
352
 
//
353
 
 
354
 
StreamResult OpenSSLStreamAdapter::Write(const void* data, size_t data_len,
355
 
                                         size_t* written, int* error) {
356
 
  LOG(LS_INFO) << "OpenSSLStreamAdapter::Write(" << data_len << ")";
357
 
 
358
 
  switch (state_) {
359
 
  case SSL_NONE:
360
 
    // pass-through in clear text
361
 
    return StreamAdapterInterface::Write(data, data_len, written, error);
362
 
 
363
 
  case SSL_WAIT:
364
 
  case SSL_CONNECTING:
365
 
    return SR_BLOCK;
366
 
 
367
 
  case SSL_CONNECTED:
368
 
    break;
369
 
 
370
 
  case SSL_ERROR:
371
 
  case SSL_CLOSED:
372
 
  default:
373
 
    if (error)
374
 
      *error = ssl_error_code_;
375
 
    return SR_ERROR;
376
 
  }
377
 
 
378
 
  // OpenSSL will return an error if we try to write zero bytes
379
 
  if (data_len == 0) {
380
 
    if (written)
381
 
      *written = 0;
382
 
    return SR_SUCCESS;
383
 
  }
384
 
 
385
 
  ssl_write_needs_read_ = false;
386
 
 
387
 
  int code = SSL_write(ssl_, data, data_len);
388
 
  int ssl_error = SSL_get_error(ssl_, code);
389
 
  switch (ssl_error) {
390
 
  case SSL_ERROR_NONE:
391
 
    LOG(LS_INFO) << " -- success";
392
 
    ASSERT(0 < code && static_cast<unsigned>(code) <= data_len);
393
 
    if (written)
394
 
      *written = code;
395
 
    return SR_SUCCESS;
396
 
  case SSL_ERROR_WANT_READ:
397
 
    LOG(LS_INFO) << " -- error want read";
398
 
    ssl_write_needs_read_ = true;
399
 
    return SR_BLOCK;
400
 
  case SSL_ERROR_WANT_WRITE:
401
 
    LOG(LS_INFO) << " -- error want write";
402
 
    return SR_BLOCK;
403
 
 
404
 
  case SSL_ERROR_ZERO_RETURN:
405
 
  default:
406
 
    Error("SSL_write", (ssl_error ? ssl_error : -1), false);
407
 
    if (error)
408
 
      *error = ssl_error_code_;
409
 
    return SR_ERROR;
410
 
  }
411
 
  // not reached
412
 
}
413
 
 
414
 
StreamResult OpenSSLStreamAdapter::Read(void* data, size_t data_len,
415
 
                                        size_t* read, int* error) {
416
 
  LOG(LS_INFO) << "OpenSSLStreamAdapter::Read(" << data_len << ")";
417
 
  switch (state_) {
418
 
    case SSL_NONE:
419
 
      // pass-through in clear text
420
 
      return StreamAdapterInterface::Read(data, data_len, read, error);
421
 
 
422
 
    case SSL_WAIT:
423
 
    case SSL_CONNECTING:
424
 
      return SR_BLOCK;
425
 
 
426
 
    case SSL_CONNECTED:
427
 
      break;
428
 
 
429
 
    case SSL_CLOSED:
430
 
      return SR_EOS;
431
 
 
432
 
    case SSL_ERROR:
433
 
    default:
434
 
      if (error)
435
 
        *error = ssl_error_code_;
436
 
      return SR_ERROR;
437
 
  }
438
 
 
439
 
  // Don't trust OpenSSL with zero byte reads
440
 
  if (data_len == 0) {
441
 
    if (read)
442
 
      *read = 0;
443
 
    return SR_SUCCESS;
444
 
  }
445
 
 
446
 
  ssl_read_needs_write_ = false;
447
 
 
448
 
  int code = SSL_read(ssl_, data, data_len);
449
 
  int ssl_error = SSL_get_error(ssl_, code);
450
 
  switch (ssl_error) {
451
 
    case SSL_ERROR_NONE:
452
 
      LOG(LS_INFO) << " -- success";
453
 
      ASSERT(0 < code && static_cast<unsigned>(code) <= data_len);
454
 
      if (read)
455
 
        *read = code;
456
 
 
457
 
      if (ssl_mode_ == SSL_MODE_DTLS) {
458
 
        // Enforce atomic reads -- this is a short read
459
 
        unsigned int pending = SSL_pending(ssl_);
460
 
 
461
 
        if (pending) {
462
 
          LOG(LS_INFO) << " -- short DTLS read. flushing";
463
 
          FlushInput(pending);
464
 
          if (error)
465
 
            *error = SSE_MSG_TRUNC;
466
 
          return SR_ERROR;
467
 
        }
468
 
      }
469
 
      return SR_SUCCESS;
470
 
    case SSL_ERROR_WANT_READ:
471
 
      LOG(LS_INFO) << " -- error want read";
472
 
      return SR_BLOCK;
473
 
    case SSL_ERROR_WANT_WRITE:
474
 
      LOG(LS_INFO) << " -- error want write";
475
 
      ssl_read_needs_write_ = true;
476
 
      return SR_BLOCK;
477
 
    case SSL_ERROR_ZERO_RETURN:
478
 
      LOG(LS_INFO) << " -- remote side closed";
479
 
      return SR_EOS;
480
 
      break;
481
 
    default:
482
 
      LOG(LS_INFO) << " -- error " << code;
483
 
      Error("SSL_read", (ssl_error ? ssl_error : -1), false);
484
 
      if (error)
485
 
        *error = ssl_error_code_;
486
 
      return SR_ERROR;
487
 
  }
488
 
  // not reached
489
 
}
490
 
 
491
 
void OpenSSLStreamAdapter::FlushInput(unsigned int left) {
492
 
  unsigned char buf[2048];
493
 
 
494
 
  while (left) {
495
 
    // This should always succeed
496
 
    int toread = (sizeof(buf) < left) ? sizeof(buf) : left;
497
 
    int code = SSL_read(ssl_, buf, toread);
498
 
 
499
 
    int ssl_error = SSL_get_error(ssl_, code);
500
 
    ASSERT(ssl_error == SSL_ERROR_NONE);
501
 
 
502
 
    if (ssl_error != SSL_ERROR_NONE) {
503
 
      LOG(LS_INFO) << " -- error " << code;
504
 
      Error("SSL_read", (ssl_error ? ssl_error : -1), false);
505
 
      return;
506
 
    }
507
 
    LOG(LS_INFO) << " -- flushed " << code << " bytes";
508
 
    left -= code;
509
 
  }
510
 
}
511
 
 
512
 
void OpenSSLStreamAdapter::Close() {
513
 
  Cleanup();
514
 
  ASSERT(state_ == SSL_CLOSED || state_ == SSL_ERROR);
515
 
  StreamAdapterInterface::Close();
516
 
}
517
 
 
518
 
StreamState OpenSSLStreamAdapter::GetState() const {
519
 
  switch (state_) {
520
 
    case SSL_WAIT:
521
 
    case SSL_CONNECTING:
522
 
      return SS_OPENING;
523
 
    case SSL_CONNECTED:
524
 
      return SS_OPEN;
525
 
    default:
526
 
      return SS_CLOSED;
527
 
  };
528
 
  // not reached
529
 
}
530
 
 
531
 
void OpenSSLStreamAdapter::OnEvent(StreamInterface* stream, int events,
532
 
                                   int err) {
533
 
  int events_to_signal = 0;
534
 
  int signal_error = 0;
535
 
  ASSERT(stream == this->stream());
536
 
  if ((events & SE_OPEN)) {
537
 
    LOG(LS_INFO) << "OpenSSLStreamAdapter::OnEvent SE_OPEN";
538
 
    if (state_ != SSL_WAIT) {
539
 
      ASSERT(state_ == SSL_NONE);
540
 
      events_to_signal |= SE_OPEN;
541
 
    } else {
542
 
      state_ = SSL_CONNECTING;
543
 
      if (int err = BeginSSL()) {
544
 
        Error("BeginSSL", err, true);
545
 
        return;
546
 
      }
547
 
    }
548
 
  }
549
 
  if ((events & (SE_READ|SE_WRITE))) {
550
 
    LOG(LS_INFO) << "OpenSSLStreamAdapter::OnEvent"
551
 
                 << ((events & SE_READ) ? " SE_READ" : "")
552
 
                 << ((events & SE_WRITE) ? " SE_WRITE" : "");
553
 
    if (state_ == SSL_NONE) {
554
 
      events_to_signal |= events & (SE_READ|SE_WRITE);
555
 
    } else if (state_ == SSL_CONNECTING) {
556
 
      if (int err = ContinueSSL()) {
557
 
        Error("ContinueSSL", err, true);
558
 
        return;
559
 
      }
560
 
    } else if (state_ == SSL_CONNECTED) {
561
 
      if (((events & SE_READ) && ssl_write_needs_read_) ||
562
 
          (events & SE_WRITE)) {
563
 
        LOG(LS_INFO) << " -- onStreamWriteable";
564
 
        events_to_signal |= SE_WRITE;
565
 
      }
566
 
      if (((events & SE_WRITE) && ssl_read_needs_write_) ||
567
 
          (events & SE_READ)) {
568
 
        LOG(LS_INFO) << " -- onStreamReadable";
569
 
        events_to_signal |= SE_READ;
570
 
      }
571
 
    }
572
 
  }
573
 
  if ((events & SE_CLOSE)) {
574
 
    LOG(LS_INFO) << "OpenSSLStreamAdapter::OnEvent(SE_CLOSE, " << err << ")";
575
 
    Cleanup();
576
 
    events_to_signal |= SE_CLOSE;
577
 
    // SE_CLOSE is the only event that uses the final parameter to OnEvent().
578
 
    ASSERT(signal_error == 0);
579
 
    signal_error = err;
580
 
  }
581
 
  if (events_to_signal)
582
 
    StreamAdapterInterface::OnEvent(stream, events_to_signal, signal_error);
583
 
}
584
 
 
585
 
int OpenSSLStreamAdapter::StartSSL() {
586
 
  ASSERT(state_ == SSL_NONE);
587
 
 
588
 
  if (StreamAdapterInterface::GetState() != SS_OPEN) {
589
 
    state_ = SSL_WAIT;
590
 
    return 0;
591
 
  }
592
 
 
593
 
  state_ = SSL_CONNECTING;
594
 
  if (int err = BeginSSL()) {
595
 
    Error("BeginSSL", err, false);
596
 
    return err;
597
 
  }
598
 
 
599
 
  return 0;
600
 
}
601
 
 
602
 
int OpenSSLStreamAdapter::BeginSSL() {
603
 
  ASSERT(state_ == SSL_CONNECTING);
604
 
  // The underlying stream has open. If we are in peer-to-peer mode
605
 
  // then a peer certificate must have been specified by now.
606
 
  ASSERT(!ssl_server_name_.empty() ||
607
 
         peer_certificate_.get() != NULL ||
608
 
         !peer_certificate_digest_algorithm_.empty());
609
 
  LOG(LS_INFO) << "BeginSSL: "
610
 
               << (!ssl_server_name_.empty() ? ssl_server_name_ :
611
 
                                               "with peer");
612
 
 
613
 
  BIO* bio = NULL;
614
 
 
615
 
  // First set up the context
616
 
  ASSERT(ssl_ctx_ == NULL);
617
 
  ssl_ctx_ = SetupSSLContext();
618
 
  if (!ssl_ctx_)
619
 
    return -1;
620
 
 
621
 
  bio = BIO_new_stream(static_cast<StreamInterface*>(stream()));
622
 
  if (!bio)
623
 
    return -1;
624
 
 
625
 
  ssl_ = SSL_new(ssl_ctx_);
626
 
  if (!ssl_) {
627
 
    BIO_free(bio);
628
 
    return -1;
629
 
  }
630
 
 
631
 
  SSL_set_app_data(ssl_, this);
632
 
 
633
 
  SSL_set_bio(ssl_, bio, bio);  // the SSL object owns the bio now.
634
 
 
635
 
  SSL_set_mode(ssl_, SSL_MODE_ENABLE_PARTIAL_WRITE |
636
 
               SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
637
 
 
638
 
  // Do the connect
639
 
  return ContinueSSL();
640
 
}
641
 
 
642
 
int OpenSSLStreamAdapter::ContinueSSL() {
643
 
  LOG(LS_INFO) << "ContinueSSL";
644
 
  ASSERT(state_ == SSL_CONNECTING);
645
 
 
646
 
  // Clear the DTLS timer
647
 
  Thread::Current()->Clear(this, MSG_TIMEOUT);
648
 
 
649
 
  int code = (role_ == SSL_CLIENT) ? SSL_connect(ssl_) : SSL_accept(ssl_);
650
 
  int ssl_error;
651
 
  switch (ssl_error = SSL_get_error(ssl_, code)) {
652
 
    case SSL_ERROR_NONE:
653
 
      LOG(LS_INFO) << " -- success";
654
 
 
655
 
      if (!SSLPostConnectionCheck(ssl_, ssl_server_name_.c_str(),
656
 
                                  peer_certificate_.get() != NULL
657
 
                                  ? peer_certificate_->x509() : NULL,
658
 
                                  peer_certificate_digest_algorithm_)) {
659
 
        LOG(LS_ERROR) << "TLS post connection check failed";
660
 
        return -1;
661
 
      }
662
 
 
663
 
      state_ = SSL_CONNECTED;
664
 
      StreamAdapterInterface::OnEvent(stream(), SE_OPEN|SE_READ|SE_WRITE, 0);
665
 
      break;
666
 
 
667
 
    case SSL_ERROR_WANT_READ: {
668
 
        LOG(LS_INFO) << " -- error want read";
669
 
#ifdef HAVE_DTLS
670
 
        struct timeval timeout;
671
 
        if (DTLSv1_get_timeout(ssl_, &timeout)) {
672
 
          int delay = timeout.tv_sec * 1000 + timeout.tv_usec/1000;
673
 
 
674
 
          Thread::Current()->PostDelayed(delay, this, MSG_TIMEOUT, 0);
675
 
        }
676
 
#endif
677
 
      }
678
 
      break;
679
 
 
680
 
    case SSL_ERROR_WANT_WRITE:
681
 
      LOG(LS_INFO) << " -- error want write";
682
 
      break;
683
 
 
684
 
    case SSL_ERROR_ZERO_RETURN:
685
 
    default:
686
 
      LOG(LS_INFO) << " -- error " << code;
687
 
      return (ssl_error != 0) ? ssl_error : -1;
688
 
  }
689
 
 
690
 
  return 0;
691
 
}
692
 
 
693
 
void OpenSSLStreamAdapter::Error(const char* context, int err, bool signal) {
694
 
  LOG(LS_WARNING) << "OpenSSLStreamAdapter::Error("
695
 
                  << context << ", " << err << ")";
696
 
  state_ = SSL_ERROR;
697
 
  ssl_error_code_ = err;
698
 
  Cleanup();
699
 
  if (signal)
700
 
    StreamAdapterInterface::OnEvent(stream(), SE_CLOSE, err);
701
 
}
702
 
 
703
 
void OpenSSLStreamAdapter::Cleanup() {
704
 
  LOG(LS_INFO) << "Cleanup";
705
 
 
706
 
  if (state_ != SSL_ERROR) {
707
 
    state_ = SSL_CLOSED;
708
 
    ssl_error_code_ = 0;
709
 
  }
710
 
 
711
 
  if (ssl_) {
712
 
    SSL_free(ssl_);
713
 
    ssl_ = NULL;
714
 
  }
715
 
  if (ssl_ctx_) {
716
 
    SSL_CTX_free(ssl_ctx_);
717
 
    ssl_ctx_ = NULL;
718
 
  }
719
 
  identity_.reset();
720
 
  peer_certificate_.reset();
721
 
 
722
 
  // Clear the DTLS timer
723
 
  Thread::Current()->Clear(this, MSG_TIMEOUT);
724
 
}
725
 
 
726
 
 
727
 
void OpenSSLStreamAdapter::OnMessage(Message* msg) {
728
 
  // Process our own messages and then pass others to the superclass
729
 
  if (MSG_TIMEOUT == msg->message_id) {
730
 
    LOG(LS_INFO) << "DTLS timeout expired";
731
 
#ifdef HAVE_DTLS
732
 
    DTLSv1_handle_timeout(ssl_);
733
 
#endif
734
 
    ContinueSSL();
735
 
  } else {
736
 
    StreamInterface::OnMessage(msg);
737
 
  }
738
 
}
739
 
 
740
 
SSL_CTX* OpenSSLStreamAdapter::SetupSSLContext() {
741
 
  SSL_CTX *ctx = NULL;
742
 
 
743
 
  if (role_ == SSL_CLIENT) {
744
 
#ifdef HAVE_DTLS
745
 
    ctx = SSL_CTX_new(ssl_mode_ == SSL_MODE_DTLS ?
746
 
        DTLSv1_client_method() : TLSv1_client_method());
747
 
#else
748
 
    ctx = SSL_CTX_new(TLSv1_client_method());
749
 
#endif
750
 
  } else {
751
 
#ifdef HAVE_DTLS
752
 
    ctx = SSL_CTX_new(ssl_mode_ == SSL_MODE_DTLS ?
753
 
        DTLSv1_server_method() : TLSv1_server_method());
754
 
#else
755
 
    ctx = SSL_CTX_new(TLSv1_server_method());
756
 
#endif
757
 
  }
758
 
  if (ctx == NULL)
759
 
    return NULL;
760
 
 
761
 
  if (identity_.get() && !identity_->ConfigureIdentity(ctx)) {
762
 
    SSL_CTX_free(ctx);
763
 
    return NULL;
764
 
  }
765
 
 
766
 
  if (peer_certificate_.get() == NULL) {  // traditional mode
767
 
    // Add the root cert to the SSL context
768
 
    if (!OpenSSLAdapter::ConfigureTrustedRootCertificates(ctx)) {
769
 
      SSL_CTX_free(ctx);
770
 
      return NULL;
771
 
    }
772
 
  }
773
 
 
774
 
  if (peer_certificate_.get() != NULL && role_ == SSL_SERVER)
775
 
    // we must specify which client cert to ask for
776
 
    SSL_CTX_add_client_CA(ctx, peer_certificate_->x509());
777
 
 
778
 
#ifdef _DEBUG
779
 
  SSL_CTX_set_info_callback(ctx, OpenSSLAdapter::SSLInfoCallback);
780
 
#endif
781
 
 
782
 
  SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER |SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
783
 
                     SSLVerifyCallback);
784
 
  SSL_CTX_set_verify_depth(ctx, 4);
785
 
  SSL_CTX_set_cipher_list(ctx, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
786
 
 
787
 
#ifdef HAVE_DTLS_SRTP
788
 
  if (!srtp_ciphers_.empty()) {
789
 
    if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_ciphers_.c_str())) {
790
 
      SSL_CTX_free(ctx);
791
 
      return NULL;
792
 
    }
793
 
  }
794
 
#endif
795
 
 
796
 
  return ctx;
797
 
}
798
 
 
799
 
int OpenSSLStreamAdapter::SSLVerifyCallback(int ok, X509_STORE_CTX* store) {
800
 
#if _DEBUG
801
 
  if (!ok) {
802
 
    char data[256];
803
 
    X509* cert = X509_STORE_CTX_get_current_cert(store);
804
 
    int depth = X509_STORE_CTX_get_error_depth(store);
805
 
    int err = X509_STORE_CTX_get_error(store);
806
 
 
807
 
    LOG(LS_INFO) << "Error with certificate at depth: " << depth;
808
 
    X509_NAME_oneline(X509_get_issuer_name(cert), data, sizeof(data));
809
 
    LOG(LS_INFO) << "  issuer  = " << data;
810
 
    X509_NAME_oneline(X509_get_subject_name(cert), data, sizeof(data));
811
 
    LOG(LS_INFO) << "  subject = " << data;
812
 
    LOG(LS_INFO) << "  err     = " << err
813
 
      << ":" << X509_verify_cert_error_string(err);
814
 
  }
815
 
#endif
816
 
 
817
 
  // Get our SSL structure from the store
818
 
  SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(
819
 
                                        store,
820
 
                                        SSL_get_ex_data_X509_STORE_CTX_idx()));
821
 
 
822
 
  OpenSSLStreamAdapter* stream =
823
 
    reinterpret_cast<OpenSSLStreamAdapter*>(SSL_get_app_data(ssl));
824
 
 
825
 
  // In peer-to-peer mode, no root cert / certificate authority was
826
 
  // specified, so the libraries knows of no certificate to accept,
827
 
  // and therefore it will necessarily call here on the first cert it
828
 
  // tries to verify.
829
 
  if (!ok && stream->peer_certificate_.get() != NULL) {
830
 
    X509* cert = X509_STORE_CTX_get_current_cert(store);
831
 
    int err = X509_STORE_CTX_get_error(store);
832
 
    // peer-to-peer mode: allow the certificate to be self-signed,
833
 
    // assuming it matches the cert that was specified.
834
 
    if (err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT &&
835
 
        X509_cmp(cert, stream->peer_certificate_->x509()) == 0) {
836
 
      LOG(LS_INFO) << "Accepted self-signed peer certificate authority";
837
 
      ok = 1;
838
 
    }
839
 
  } else if (!ok && !stream->peer_certificate_digest_algorithm_.empty()) {
840
 
    X509* cert = X509_STORE_CTX_get_current_cert(store);
841
 
    int err = X509_STORE_CTX_get_error(store);
842
 
 
843
 
    // peer-to-peer mode: allow the certificate to be self-signed,
844
 
    // assuming it matches the digest that was specified.
845
 
    if (err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT) {
846
 
      unsigned char digest[EVP_MAX_MD_SIZE];
847
 
      std::size_t digest_length;
848
 
 
849
 
      if (OpenSSLCertificate::
850
 
         ComputeDigest(cert,
851
 
                       stream->peer_certificate_digest_algorithm_,
852
 
                       digest, sizeof(digest),
853
 
                       &digest_length)) {
854
 
        Buffer computed_digest(digest, digest_length);
855
 
        if (computed_digest == stream->peer_certificate_digest_value_) {
856
 
          LOG(LS_INFO) <<
857
 
              "Accepted self-signed peer certificate authority";
858
 
          ok = 1;
859
 
        }
860
 
      }
861
 
    }
862
 
  } else if (!ok && OpenSSLAdapter::custom_verify_callback_) {
863
 
    // this applies only in traditional mode
864
 
    void* cert =
865
 
        reinterpret_cast<void*>(X509_STORE_CTX_get_current_cert(store));
866
 
    if (OpenSSLAdapter::custom_verify_callback_(cert)) {
867
 
      stream->custom_verification_succeeded_ = true;
868
 
      LOG(LS_INFO) << "validated certificate using custom callback";
869
 
      ok = 1;
870
 
    }
871
 
  }
872
 
 
873
 
  if (!ok && stream->ignore_bad_cert()) {
874
 
    LOG(LS_WARNING) << "Ignoring cert error while verifying cert chain";
875
 
    ok = 1;
876
 
  }
877
 
 
878
 
  return ok;
879
 
}
880
 
 
881
 
// This code is taken from the "Network Security with OpenSSL"
882
 
// sample in chapter 5
883
 
bool OpenSSLStreamAdapter::SSLPostConnectionCheck(SSL* ssl,
884
 
                                                  const char* server_name,
885
 
                                                  const X509* peer_cert,
886
 
                                                  const std::string
887
 
                                                  &peer_digest) {
888
 
  ASSERT(server_name != NULL);
889
 
  bool ok;
890
 
  if (server_name[0] != '\0') {  // traditional mode
891
 
    ok = OpenSSLAdapter::VerifyServerName(ssl, server_name, ignore_bad_cert());
892
 
 
893
 
    if (ok) {
894
 
      ok = (SSL_get_verify_result(ssl) == X509_V_OK ||
895
 
            custom_verification_succeeded_);
896
 
    }
897
 
  } else {  // peer-to-peer mode
898
 
    ASSERT((peer_cert != NULL) || (!peer_digest.empty()));
899
 
    // no server name validation
900
 
    ok = true;
901
 
  }
902
 
 
903
 
  if (!ok && ignore_bad_cert()) {
904
 
    LOG(LS_ERROR) << "SSL_get_verify_result(ssl) = "
905
 
                  << SSL_get_verify_result(ssl);
906
 
    LOG(LS_INFO) << "Other TLS post connection checks failed.";
907
 
    ok = true;
908
 
  }
909
 
 
910
 
  return ok;
911
 
}
912
 
 
913
 
bool OpenSSLStreamAdapter::HaveDtls() {
914
 
#ifdef HAVE_DTLS
915
 
  return true;
916
 
#else
917
 
  return false;
918
 
#endif
919
 
}
920
 
 
921
 
bool OpenSSLStreamAdapter::HaveDtlsSrtp() {
922
 
#ifdef HAVE_DTLS_SRTP
923
 
  return true;
924
 
#else
925
 
  return false;
926
 
#endif
927
 
}
928
 
 
929
 
bool OpenSSLStreamAdapter::HaveExporter() {
930
 
#ifdef HAVE_DTLS_SRTP
931
 
  return true;
932
 
#else
933
 
  return false;
934
 
#endif
935
 
}
936
 
 
937
 
}  // namespace talk_base
938
 
 
939
 
#endif  // HAVE_OPENSSL_SSL_H