Home | History | Annotate | Download | only in base
      1 /*
      2  * libjingle
      3  * Copyright 2011, Google Inc.
      4  * Copyright 2011, RTFM, Inc.
      5  *
      6  * Redistribution and use in source and binary forms, with or without
      7  * modification, are permitted provided that the following conditions are met:
      8  *
      9  *  1. Redistributions of source code must retain the above copyright notice,
     10  *     this list of conditions and the following disclaimer.
     11  *  2. Redistributions in binary form must reproduce the above copyright notice,
     12  *     this list of conditions and the following disclaimer in the documentation
     13  *     and/or other materials provided with the distribution.
     14  *  3. The name of the author may not be used to endorse or promote products
     15  *     derived from this software without specific prior written permission.
     16  *
     17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
     18  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
     19  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
     20  * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     21  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     22  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
     23  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
     24  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
     25  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
     26  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     27  */
     28 
     29 #include "talk/p2p/base/dtlstransportchannel.h"
     30 
     31 #include "talk/base/buffer.h"
     32 #include "talk/base/messagequeue.h"
     33 #include "talk/base/stream.h"
     34 #include "talk/base/sslstreamadapter.h"
     35 #include "talk/base/thread.h"
     36 #include "talk/p2p/base/common.h"
     37 
     38 namespace cricket {
     39 
     40 // We don't pull the RTP constants from rtputils.h, to avoid a layer violation.
     41 static const size_t kDtlsRecordHeaderLen = 13;
     42 static const size_t kMaxDtlsPacketLen = 2048;
     43 static const size_t kMinRtpPacketLen = 12;
     44 
     45 static bool IsDtlsPacket(const char* data, size_t len) {
     46   const uint8* u = reinterpret_cast<const uint8*>(data);
     47   return (len >= kDtlsRecordHeaderLen && (u[0] > 19 && u[0] < 64));
     48 }
     49 static bool IsRtpPacket(const char* data, size_t len) {
     50   const uint8* u = reinterpret_cast<const uint8*>(data);
     51   return (len >= kMinRtpPacketLen && (u[0] & 0xC0) == 0x80);
     52 }
     53 
     54 talk_base::StreamResult StreamInterfaceChannel::Read(void* buffer,
     55                                                      size_t buffer_len,
     56                                                      size_t* read,
     57                                                      int* error) {
     58   if (state_ == talk_base::SS_CLOSED)
     59     return talk_base::SR_EOS;
     60   if (state_ == talk_base::SS_OPENING)
     61     return talk_base::SR_BLOCK;
     62 
     63   return fifo_.Read(buffer, buffer_len, read, error);
     64 }
     65 
     66 talk_base::StreamResult StreamInterfaceChannel::Write(const void* data,
     67                                                       size_t data_len,
     68                                                       size_t* written,
     69                                                       int* error) {
     70   // Always succeeds, since this is an unreliable transport anyway.
     71   // TODO: Should this block if channel_'s temporarily unwritable?
     72   channel_->SendPacket(static_cast<const char*>(data), data_len);
     73   if (written) {
     74     *written = data_len;
     75   }
     76   return talk_base::SR_SUCCESS;
     77 }
     78 
     79 bool StreamInterfaceChannel::OnPacketReceived(const char* data, size_t size) {
     80   // We force a read event here to ensure that we don't overflow our FIFO.
     81   // Under high packet rate this can occur if we wait for the FIFO to post its
     82   // own SE_READ.
     83   bool ret = (fifo_.WriteAll(data, size, NULL, NULL) == talk_base::SR_SUCCESS);
     84   if (ret) {
     85     SignalEvent(this, talk_base::SE_READ, 0);
     86   }
     87   return ret;
     88 }
     89 
     90 void StreamInterfaceChannel::OnEvent(talk_base::StreamInterface* stream,
     91                                      int sig, int err) {
     92   SignalEvent(this, sig, err);
     93 }
     94 
     95 DtlsTransportChannelWrapper::DtlsTransportChannelWrapper(
     96                                            Transport* transport,
     97                                            TransportChannelImpl* channel)
     98     : TransportChannelImpl(channel->content_name(), channel->component()),
     99       transport_(transport),
    100       worker_thread_(talk_base::Thread::Current()),
    101       channel_(channel),
    102       downward_(NULL),
    103       dtls_state_(STATE_NONE),
    104       local_identity_(NULL),
    105       dtls_role_(talk_base::SSL_CLIENT) {
    106   channel_->SignalReadableState.connect(this,
    107       &DtlsTransportChannelWrapper::OnReadableState);
    108   channel_->SignalWritableState.connect(this,
    109       &DtlsTransportChannelWrapper::OnWritableState);
    110   channel_->SignalReadPacket.connect(this,
    111       &DtlsTransportChannelWrapper::OnReadPacket);
    112   channel_->SignalReadyToSend.connect(this,
    113       &DtlsTransportChannelWrapper::OnReadyToSend);
    114   channel_->SignalRequestSignaling.connect(this,
    115       &DtlsTransportChannelWrapper::OnRequestSignaling);
    116   channel_->SignalCandidateReady.connect(this,
    117       &DtlsTransportChannelWrapper::OnCandidateReady);
    118   channel_->SignalCandidatesAllocationDone.connect(this,
    119       &DtlsTransportChannelWrapper::OnCandidatesAllocationDone);
    120   channel_->SignalRoleConflict.connect(this,
    121       &DtlsTransportChannelWrapper::OnRoleConflict);
    122   channel_->SignalRouteChange.connect(this,
    123       &DtlsTransportChannelWrapper::OnRouteChange);
    124 }
    125 
    126 DtlsTransportChannelWrapper::~DtlsTransportChannelWrapper() {
    127 }
    128 
    129 void DtlsTransportChannelWrapper::Connect() {
    130   // We should only get a single call to Connect.
    131   ASSERT(dtls_state_ == STATE_NONE ||
    132          dtls_state_ == STATE_OFFERED ||
    133          dtls_state_ == STATE_ACCEPTED);
    134   channel_->Connect();
    135 }
    136 
    137 void DtlsTransportChannelWrapper::Reset() {
    138   channel_->Reset();
    139   set_writable(false);
    140   set_readable(false);
    141 
    142   // Re-call SetupDtls()
    143   if (!SetupDtls()) {
    144     LOG_J(LS_ERROR, this) << "Error re-initializing DTLS";
    145     dtls_state_ = STATE_CLOSED;
    146     return;
    147   }
    148 
    149   dtls_state_ = STATE_ACCEPTED;
    150 }
    151 
    152 bool DtlsTransportChannelWrapper::SetLocalIdentity(
    153     talk_base::SSLIdentity* identity) {
    154   if (dtls_state_ == STATE_OPEN && identity == local_identity_) {
    155     return true;
    156   }
    157 
    158   // TODO(ekr (at) rtfm.com): Forbid this if Connect() has been called.
    159   if (dtls_state_ != STATE_NONE) {
    160     LOG_J(LS_ERROR, this) << "Can't set DTLS local identity in this state";
    161     return false;
    162   }
    163 
    164   if (identity) {
    165     local_identity_ = identity;
    166     dtls_state_ = STATE_OFFERED;
    167   } else {
    168     LOG_J(LS_INFO, this) << "NULL DTLS identity supplied. Not doing DTLS";
    169   }
    170 
    171   return true;
    172 }
    173 
    174 void DtlsTransportChannelWrapper::SetIceRole(IceRole role) {
    175   // TODO(ekr (at) rtfm.com): Forbid this if Connect() has been called.
    176   ASSERT(dtls_state_ < STATE_ACCEPTED);
    177 
    178   // Set the role that is most conformant with RFC 5763, Section 5, bullet 1:
    179   //     The endpoint that is the offerer MUST [...] be prepared to receive
    180   //     a client_hello before it receives the answer.
    181   // (IOW, the offerer is the server, and the answerer is the client).
    182   dtls_role_ = (role == ICEROLE_CONTROLLING) ?
    183       talk_base::SSL_SERVER : talk_base::SSL_CLIENT;
    184 
    185   channel_->SetIceRole(role);
    186 }
    187 
    188 bool DtlsTransportChannelWrapper::SetRemoteFingerprint(
    189     const std::string& digest_alg,
    190     const uint8* digest,
    191     size_t digest_len) {
    192 
    193   talk_base::Buffer remote_fingerprint_value(digest, digest_len);
    194 
    195   if ((dtls_state_ == STATE_OPEN) &&
    196       (remote_fingerprint_value_ == remote_fingerprint_value)) {
    197     return true;
    198   }
    199 
    200   // Allow SetRemoteFingerprint with a NULL digest even if SetLocalIdentity
    201   // hasn't been called.
    202   if (dtls_state_ > STATE_OFFERED ||
    203       (dtls_state_ == STATE_NONE && !digest_alg.empty())) {
    204     LOG_J(LS_ERROR, this) << "Can't set DTLS remote settings in this state";
    205     return false;
    206   }
    207 
    208   if (digest_alg.empty()) {
    209     LOG_J(LS_INFO, this) << "Other side didn't support DTLS";
    210     dtls_state_ = STATE_NONE;
    211     return true;
    212   }
    213 
    214   // At this point we know we are doing DTLS
    215   remote_fingerprint_value.TransferTo(&remote_fingerprint_value_);
    216   remote_fingerprint_algorithm_ = digest_alg;
    217 
    218   if (!SetupDtls()) {
    219     dtls_state_ = STATE_CLOSED;
    220     return false;
    221   }
    222 
    223   dtls_state_ = STATE_ACCEPTED;
    224   return true;
    225 }
    226 
    227 bool DtlsTransportChannelWrapper::SetupDtls() {
    228   StreamInterfaceChannel* downward =
    229       new StreamInterfaceChannel(worker_thread_, channel_);
    230 
    231   dtls_.reset(talk_base::SSLStreamAdapter::Create(downward));
    232   if (!dtls_) {
    233     LOG_J(LS_ERROR, this) << "Failed to create DTLS adapter";
    234     delete downward;
    235     return false;
    236   }
    237 
    238   downward_ = downward;
    239 
    240   dtls_->SetIdentity(local_identity_->GetReference());
    241   dtls_->SetMode(talk_base::SSL_MODE_DTLS);
    242   dtls_->SetServerRole(dtls_role_);
    243   dtls_->SignalEvent.connect(this, &DtlsTransportChannelWrapper::OnDtlsEvent);
    244   if (!dtls_->SetPeerCertificateDigest(
    245           remote_fingerprint_algorithm_,
    246           reinterpret_cast<unsigned char *>(remote_fingerprint_value_.data()),
    247           remote_fingerprint_value_.length())) {
    248     LOG_J(LS_ERROR, this) << "Couldn't set DTLS certificate digest";
    249     return false;
    250   }
    251 
    252   // Set up DTLS-SRTP, if it's been enabled.
    253   if (!srtp_ciphers_.empty()) {
    254     if (!dtls_->SetDtlsSrtpCiphers(srtp_ciphers_)) {
    255       LOG_J(LS_ERROR, this) << "Couldn't set DTLS-SRTP ciphers";
    256       return false;
    257     }
    258   } else {
    259     LOG_J(LS_INFO, this) << "Not using DTLS";
    260   }
    261 
    262   LOG_J(LS_INFO, this) << "DTLS setup complete";
    263   return true;
    264 }
    265 
    266 bool DtlsTransportChannelWrapper::SetSrtpCiphers(const std::vector<std::string>&
    267                                                  ciphers) {
    268   // SRTP ciphers must be set before the DTLS handshake starts.
    269   // TODO(juberti): In multiplex situations, we may end up calling this function
    270   // once for each muxed channel. Depending on the order of calls, this may
    271   // result in slightly undesired results, e.g. 32 vs 80-bit MAC. The right way to
    272   // fix this would be for the TransportProxyChannels to intersect the ciphers
    273   // instead of overwriting, so that "80" followed by "32, 80" results in "80".
    274   if (dtls_state_ != STATE_NONE &&
    275       dtls_state_ != STATE_OFFERED &&
    276       dtls_state_ != STATE_ACCEPTED) {
    277     ASSERT(false);
    278     return false;
    279   }
    280 
    281   srtp_ciphers_ = ciphers;
    282   return true;
    283 }
    284 
    285 bool DtlsTransportChannelWrapper::GetSrtpCipher(std::string* cipher) {
    286   if (dtls_state_ != STATE_OPEN) {
    287     return false;
    288   }
    289 
    290   return dtls_->GetDtlsSrtpCipher(cipher);
    291 }
    292 
    293 
    294 // Called from upper layers to send a media packet.
    295 int DtlsTransportChannelWrapper::SendPacket(const char* data, size_t size,
    296                                             int flags) {
    297   int result = -1;
    298 
    299   switch (dtls_state_) {
    300     case STATE_OFFERED:
    301       // We don't know if we are doing DTLS yet, so we can't send a packet.
    302       // TODO(ekr (at) rtfm.com): assert here?
    303       result = -1;
    304       break;
    305 
    306     case STATE_STARTED:
    307     case STATE_ACCEPTED:
    308       // Can't send data until the connection is active
    309       result = -1;
    310       break;
    311 
    312     case STATE_OPEN:
    313       if (flags & PF_SRTP_BYPASS) {
    314         ASSERT(!srtp_ciphers_.empty());
    315         if (!IsRtpPacket(data, size)) {
    316           result = false;
    317           break;
    318         }
    319 
    320         result = channel_->SendPacket(data, size);
    321       } else {
    322         result = (dtls_->WriteAll(data, size, NULL, NULL) ==
    323           talk_base::SR_SUCCESS) ? static_cast<int>(size) : -1;
    324       }
    325       break;
    326       // Not doing DTLS.
    327     case STATE_NONE:
    328       result = channel_->SendPacket(data, size);
    329       break;
    330 
    331     case STATE_CLOSED:  // Can't send anything when we're closed.
    332       return -1;
    333   }
    334 
    335   return result;
    336 }
    337 
    338 // The state transition logic here is as follows:
    339 // (1) If we're not doing DTLS-SRTP, then the state is just the
    340 //     state of the underlying impl()
    341 // (2) If we're doing DTLS-SRTP:
    342 //     - Prior to the DTLS handshake, the state is neither readable or
    343 //       writable
    344 //     - When the impl goes writable for the first time we
    345 //       start the DTLS handshake
    346 //     - Once the DTLS handshake completes, the state is that of the
    347 //       impl again
    348 void DtlsTransportChannelWrapper::OnReadableState(TransportChannel* channel) {
    349   ASSERT(talk_base::Thread::Current() == worker_thread_);
    350   ASSERT(channel == channel_);
    351   LOG_J(LS_VERBOSE, this)
    352       << "DTLSTransportChannelWrapper: channel readable state changed";
    353 
    354   if (dtls_state_ == STATE_NONE || dtls_state_ == STATE_OPEN) {
    355     set_readable(channel_->readable());
    356     // Note: SignalReadableState fired by set_readable.
    357   }
    358 }
    359 
    360 void DtlsTransportChannelWrapper::OnWritableState(TransportChannel* channel) {
    361   ASSERT(talk_base::Thread::Current() == worker_thread_);
    362   ASSERT(channel == channel_);
    363   LOG_J(LS_VERBOSE, this)
    364       << "DTLSTransportChannelWrapper: channel writable state changed";
    365 
    366   switch (dtls_state_) {
    367     case STATE_NONE:
    368     case STATE_OPEN:
    369       set_writable(channel_->writable());
    370       // Note: SignalWritableState fired by set_writable.
    371       break;
    372 
    373     case STATE_OFFERED:
    374       // Do nothing
    375       break;
    376 
    377     case STATE_ACCEPTED:
    378       if (!MaybeStartDtls()) {
    379         // This should never happen:
    380         // Because we are operating in a nonblocking mode and all
    381         // incoming packets come in via OnReadPacket(), which rejects
    382         // packets in this state, the incoming queue must be empty. We
    383         // ignore write errors, thus any errors must be because of
    384         // configuration and therefore are our fault.
    385         // Note that in non-debug configurations, failure in
    386         // MaybeStartDtls() changes the state to STATE_CLOSED.
    387         ASSERT(false);
    388       }
    389       break;
    390 
    391     case STATE_STARTED:
    392       // Do nothing
    393       break;
    394 
    395     case STATE_CLOSED:
    396       // Should not happen. Do nothing
    397       break;
    398   }
    399 }
    400 
    401 void DtlsTransportChannelWrapper::OnReadPacket(TransportChannel* channel,
    402                                                const char* data, size_t size,
    403                                                int flags) {
    404   ASSERT(talk_base::Thread::Current() == worker_thread_);
    405   ASSERT(channel == channel_);
    406   ASSERT(flags == 0);
    407 
    408   switch (dtls_state_) {
    409     case STATE_NONE:
    410       // We are not doing DTLS
    411       SignalReadPacket(this, data, size, 0);
    412       break;
    413 
    414     case STATE_OFFERED:
    415       // Currently drop the packet, but we might in future
    416       // decide to take this as evidence that the other
    417       // side is ready to do DTLS and start the handshake
    418       // on our end
    419       LOG_J(LS_WARNING, this) << "Received packet before we know if we are doing "
    420                               << "DTLS or not; dropping";
    421       break;
    422 
    423     case STATE_ACCEPTED:
    424       // Drop packets received before DTLS has actually started
    425       LOG_J(LS_INFO, this) << "Dropping packet received before DTLS started";
    426       break;
    427 
    428     case STATE_STARTED:
    429     case STATE_OPEN:
    430       // We should only get DTLS or SRTP packets; STUN's already been demuxed.
    431       // Is this potentially a DTLS packet?
    432       if (IsDtlsPacket(data, size)) {
    433         if (!HandleDtlsPacket(data, size)) {
    434           LOG_J(LS_ERROR, this) << "Failed to handle DTLS packet";
    435           return;
    436         }
    437       } else {
    438         // Not a DTLS packet; our handshake should be complete by now.
    439         if (dtls_state_ != STATE_OPEN) {
    440           LOG_J(LS_ERROR, this) << "Received non-DTLS packet before DTLS complete";
    441           return;
    442         }
    443 
    444         // And it had better be a SRTP packet.
    445         if (!IsRtpPacket(data, size)) {
    446           LOG_J(LS_ERROR, this) << "Received unexpected non-DTLS packet";
    447           return;
    448         }
    449 
    450         // Sanity check.
    451         ASSERT(!srtp_ciphers_.empty());
    452 
    453         // Signal this upwards as a bypass packet.
    454         SignalReadPacket(this, data, size, PF_SRTP_BYPASS);
    455       }
    456       break;
    457     case STATE_CLOSED:
    458       // This shouldn't be happening. Drop the packet
    459       break;
    460   }
    461 }
    462 
    463 void DtlsTransportChannelWrapper::OnReadyToSend(TransportChannel* channel) {
    464   if (writable()) {
    465     SignalReadyToSend(this);
    466   }
    467 }
    468 
    469 void DtlsTransportChannelWrapper::OnDtlsEvent(talk_base::StreamInterface* dtls,
    470                                               int sig, int err) {
    471   ASSERT(talk_base::Thread::Current() == worker_thread_);
    472   ASSERT(dtls == dtls_.get());
    473   if (sig & talk_base::SE_OPEN) {
    474     // This is the first time.
    475     LOG_J(LS_INFO, this) << "DTLS handshake complete";
    476     if (dtls_->GetState() == talk_base::SS_OPEN) {
    477       // The check for OPEN shouldn't be necessary but let's make
    478       // sure we don't accidentally frob the state if it's closed.
    479       dtls_state_ = STATE_OPEN;
    480 
    481       set_readable(true);
    482       set_writable(true);
    483     }
    484   }
    485   if (sig & talk_base::SE_READ) {
    486     char buf[kMaxDtlsPacketLen];
    487     size_t read;
    488     if (dtls_->Read(buf, sizeof(buf), &read, NULL) == talk_base::SR_SUCCESS) {
    489       SignalReadPacket(this, buf, read, 0);
    490     }
    491   }
    492   if (sig & talk_base::SE_CLOSE) {
    493     ASSERT(sig == talk_base::SE_CLOSE);  // SE_CLOSE should be by itself.
    494     if (!err) {
    495       LOG_J(LS_INFO, this) << "DTLS channel closed";
    496     } else {
    497       LOG_J(LS_INFO, this) << "DTLS channel error, code=" << err;
    498     }
    499 
    500     set_readable(false);
    501     set_writable(false);
    502     dtls_state_ = STATE_CLOSED;
    503   }
    504 }
    505 
    506 bool DtlsTransportChannelWrapper::MaybeStartDtls() {
    507   if (channel_->writable()) {
    508     if (dtls_->StartSSLWithPeer()) {
    509       LOG_J(LS_ERROR, this) << "Couldn't start DTLS handshake";
    510       dtls_state_ = STATE_CLOSED;
    511       return false;
    512     }
    513     LOG_J(LS_INFO, this)
    514       << "DtlsTransportChannelWrapper: Started DTLS handshake";
    515 
    516     dtls_state_ = STATE_STARTED;
    517   }
    518   return true;
    519 }
    520 
    521 // Called from OnReadPacket when a DTLS packet is received.
    522 bool DtlsTransportChannelWrapper::HandleDtlsPacket(const char* data,
    523                                                    size_t size) {
    524   // Sanity check we're not passing junk that
    525   // just looks like DTLS.
    526   const uint8* tmp_data = reinterpret_cast<const uint8* >(data);
    527   size_t tmp_size = size;
    528   while (tmp_size > 0) {
    529     if (tmp_size < kDtlsRecordHeaderLen)
    530       return false;  // Too short for the header
    531 
    532     size_t record_len = (tmp_data[11] << 8) | (tmp_data[12]);
    533     if ((record_len + kDtlsRecordHeaderLen) > tmp_size)
    534       return false;  // Body too short
    535 
    536     tmp_data += record_len + kDtlsRecordHeaderLen;
    537     tmp_size -= record_len + kDtlsRecordHeaderLen;
    538   }
    539 
    540   // Looks good. Pass to the SIC which ends up being passed to
    541   // the DTLS stack.
    542   return downward_->OnPacketReceived(data, size);
    543 }
    544 
    545 void DtlsTransportChannelWrapper::OnRequestSignaling(
    546     TransportChannelImpl* channel) {
    547   ASSERT(channel == channel_);
    548   SignalRequestSignaling(this);
    549 }
    550 
    551 void DtlsTransportChannelWrapper::OnCandidateReady(
    552     TransportChannelImpl* channel, const Candidate& c) {
    553   ASSERT(channel == channel_);
    554   SignalCandidateReady(this, c);
    555 }
    556 
    557 void DtlsTransportChannelWrapper::OnCandidatesAllocationDone(
    558     TransportChannelImpl* channel) {
    559   ASSERT(channel == channel_);
    560   SignalCandidatesAllocationDone(this);
    561 }
    562 
    563 void DtlsTransportChannelWrapper::OnRoleConflict(
    564     TransportChannelImpl* channel) {
    565   ASSERT(channel == channel_);
    566   SignalRoleConflict(this);
    567 }
    568 
    569 void DtlsTransportChannelWrapper::OnRouteChange(
    570     TransportChannel* channel, const Candidate& candidate) {
    571   ASSERT(channel == channel_);
    572   SignalRouteChange(this, candidate);
    573 }
    574 
    575 }  // namespace cricket
    576