summaryrefslogtreecommitdiffstats
path: root/libtransport/src/implementation/p2psecure_socket_consumer.cc
blob: 8c7c175b2711f1137b656260889c6f5748db28fc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
/*
 * Copyright (c) 2017-2020 Cisco and/or its affiliates.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <implementation/p2psecure_socket_consumer.h>
#include <interfaces/tls_socket_consumer.h>
#include <openssl/bio.h>
#include <openssl/ssl.h>
#include <openssl/tls1.h>

#include <random>

namespace transport {
namespace implementation {

void P2PSecureConsumerSocket::setInterestPayload(
    interface::ConsumerSocket &c, const core::Interest &interest) {
  Interest &int2 = const_cast<Interest &>(interest);
  random_suffix_ = int2.getName().getSuffix();

  if (payload_ != NULL) int2.appendPayload(std::move(payload_));
}

/* Return the number of read bytes in the return param */
int readOld(BIO *b, char *buf, int size) {
  if (size < 0) return size;

  P2PSecureConsumerSocket *socket;
  socket = (P2PSecureConsumerSocket *)BIO_get_data(b);

  std::unique_lock<std::mutex> lck(socket->mtx_);

  if (!socket->something_to_read_) {
    if (!socket->transport_protocol_->isRunning()) {
      socket->network_name_.setSuffix(socket->random_suffix_);
      socket->ConsumerSocket::asyncConsume(socket->network_name_);
    }

    if (!socket->something_to_read_) socket->cv_.wait(lck);
  }

  size_t size_to_read, read;
  size_t chain_size = socket->head_->length();

  if (socket->head_->isChained())
    chain_size = socket->head_->computeChainDataLength();

  if (chain_size > (size_t)size) {
    read = size_to_read = (size_t)size;
  } else {
    read = size_to_read = chain_size;
    socket->something_to_read_ = false;
  }

  while (size_to_read) {
    if (socket->head_->length() < size_to_read) {
      std::memcpy(buf, socket->head_->data(), socket->head_->length());
      size_to_read -= socket->head_->length();
      buf += socket->head_->length();
      socket->head_ = socket->head_->pop();
    } else {
      std::memcpy(buf, socket->head_->data(), size_to_read);
      socket->head_->trimStart(size_to_read);
      size_to_read = 0;
    }
  }

  return read;
}

/* Return the number of read bytes in readbytes */
int read(BIO *b, char *buf, size_t size, size_t *readbytes) {
  int ret;

  if (size > INT_MAX) size = INT_MAX;

  ret = readOld(b, buf, (int)size);

  if (ret <= 0) {
    *readbytes = 0;
    return ret;
  }

  *readbytes = (size_t)ret;

  return 1;
}

/* Return the number of written bytes in the return param */
int writeOld(BIO *b, const char *buf, int num) {
  P2PSecureConsumerSocket *socket;
  socket = (P2PSecureConsumerSocket *)BIO_get_data(b);

  socket->payload_ = utils::MemBuf::copyBuffer(buf, num);

  socket->ConsumerSocket::setSocketOption(
      ConsumerCallbacksOptions::INTEREST_OUTPUT,
      (ConsumerInterestCallback)std::bind(
          &P2PSecureConsumerSocket::setInterestPayload, socket,
          std::placeholders::_1, std::placeholders::_2));

  return num;
}

/* Return the number of written bytes in written */
int write(BIO *b, const char *buf, size_t size, size_t *written) {
  int ret;

  if (size > INT_MAX) size = INT_MAX;

  ret = writeOld(b, buf, (int)size);

  if (ret <= 0) {
    *written = 0;
    return ret;
  }

  *written = (size_t)ret;

  return 1;
}

long ctrl(BIO *b, int cmd, long num, void *ptr) { return 1; }

int P2PSecureConsumerSocket::addHicnKeyIdCb(SSL *s, unsigned int ext_type,
                                            unsigned int context,
                                            const unsigned char **out,
                                            size_t *outlen, X509 *x,
                                            size_t chainidx, int *al,
                                            void *add_arg) {
  if (ext_type == 100) {
    *out = (unsigned char *)malloc(4);
    *(uint32_t *)*out = 10;
    *outlen = 4;
  }
  return 1;
}

void P2PSecureConsumerSocket::freeHicnKeyIdCb(SSL *s, unsigned int ext_type,
                                              unsigned int context,
                                              const unsigned char *out,
                                              void *add_arg) {
  free(const_cast<unsigned char *>(out));
}

int P2PSecureConsumerSocket::parseHicnKeyIdCb(SSL *s, unsigned int ext_type,
                                              unsigned int context,
                                              const unsigned char *in,
                                              size_t inlen, X509 *x,
                                              size_t chainidx, int *al,
                                              void *add_arg) {
  P2PSecureConsumerSocket *socket =
      reinterpret_cast<P2PSecureConsumerSocket *>(add_arg);
  if (ext_type == 100) {
    memcpy(&socket->secure_prefix_, in, sizeof(ip_prefix_t));
  }
  return 1;
}

P2PSecureConsumerSocket::P2PSecureConsumerSocket(
    interface::ConsumerSocket *consumer, int handshake_protocol,
    int transport_protocol)
    : ConsumerSocket(consumer, handshake_protocol),
      name_(),
      tls_consumer_(nullptr),
      decrypted_content_(),
      payload_(),
      head_(),
      something_to_read_(false),
      content_downloaded_(false),
      random_suffix_(),
      secure_prefix_(),
      producer_namespace_(),
      read_callback_decrypted_(),
      mtx_(),
      cv_(),
      protocol_(transport_protocol) {
  /* Create the (d)TLS state */
  const SSL_METHOD *meth = TLS_client_method();
  ctx_ = SSL_CTX_new(meth);

  int result =
      SSL_CTX_set_ciphersuites(ctx_,
                               "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_"
                               "SHA256:TLS_AES_128_GCM_SHA256");
  if (result != 1) {
    throw errors::RuntimeException(
        "Unable to set cipher list on TLS subsystem. Aborting.");
  }

  SSL_CTX_set_min_proto_version(ctx_, TLS1_3_VERSION);
  SSL_CTX_set_max_proto_version(ctx_, TLS1_3_VERSION);
  SSL_CTX_set_verify(ctx_, SSL_VERIFY_NONE, NULL);
  SSL_CTX_set_ssl_version(ctx_, meth);

  result = SSL_CTX_add_custom_ext(
      ctx_, 100, SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
      P2PSecureConsumerSocket::addHicnKeyIdCb,
      P2PSecureConsumerSocket::freeHicnKeyIdCb, NULL,
      P2PSecureConsumerSocket::parseHicnKeyIdCb, this);

  ssl_ = SSL_new(ctx_);

  bio_meth_ = BIO_meth_new(BIO_TYPE_CONNECT, "secure consumer socket");
  BIO_meth_set_read(bio_meth_, readOld);
  BIO_meth_set_write(bio_meth_, writeOld);
  BIO_meth_set_ctrl(bio_meth_, ctrl);
  BIO *bio = BIO_new(bio_meth_);
  BIO_set_init(bio, 1);
  BIO_set_data(bio, this);
  SSL_set_bio(ssl_, bio, bio);

  std::default_random_engine generator;
  std::uniform_int_distribution<int> distribution(
      1, std::numeric_limits<uint32_t>::max());
  random_suffix_ = 0;

  this->ConsumerSocket::setSocketOption(ConsumerCallbacksOptions::READ_CALLBACK,
                                        this);
};

P2PSecureConsumerSocket::~P2PSecureConsumerSocket() {
  BIO_meth_free(bio_meth_);
  SSL_shutdown(ssl_);
}

int P2PSecureConsumerSocket::handshake() {
  int result = 1;

  if (!(SSL_in_before(this->ssl_) || SSL_in_init(this->ssl_))) {
    return 1;
  }

  ConsumerSocket::getSocketOption(MAX_WINDOW_SIZE, old_max_win_);
  ConsumerSocket::getSocketOption(CURRENT_WINDOW_SIZE, old_current_win_);

  ConsumerSocket::setSocketOption(MAX_WINDOW_SIZE, (double)1.0);
  ConsumerSocket::setSocketOption(CURRENT_WINDOW_SIZE, (double)1.0);

  network_name_ = producer_namespace_.getRandomName();
  network_name_.setSuffix(0);

  TRANSPORT_LOGD("Start handshake at %s", network_name_.toString().c_str());
  result = SSL_connect(this->ssl_);

  return result;
}

void P2PSecureConsumerSocket::initSessionSocket() {
  tls_consumer_ =
      std::make_shared<TLSConsumerSocket>(nullptr, this->protocol_, this->ssl_);
  tls_consumer_->setInterface(
      new interface::TLSConsumerSocket(tls_consumer_.get()));

  ConsumerTimerCallback *stats_summary_callback = nullptr;
  this->getSocketOption(ConsumerCallbacksOptions::STATS_SUMMARY,
                        &stats_summary_callback);

  uint32_t lifetime;
  this->getSocketOption(GeneralTransportOptions::INTEREST_LIFETIME, lifetime);

  tls_consumer_->setSocketOption(GeneralTransportOptions::INTEREST_LIFETIME,
                                 lifetime);
  tls_consumer_->setSocketOption(ConsumerCallbacksOptions::READ_CALLBACK,
                                 read_callback_decrypted_);
  tls_consumer_->setSocketOption(ConsumerCallbacksOptions::STATS_SUMMARY,
                                 *stats_summary_callback);
  tls_consumer_->setSocketOption(GeneralTransportOptions::STATS_INTERVAL,
                                 this->timer_interval_milliseconds_);
  tls_consumer_->setSocketOption(MAX_WINDOW_SIZE, old_max_win_);
  tls_consumer_->setSocketOption(CURRENT_WINDOW_SIZE, old_current_win_);
  tls_consumer_->connect();
}

int P2PSecureConsumerSocket::consume(const Name &name) {
  if (transport_protocol_->isRunning()) {
    return CONSUMER_BUSY;
  }

  if (handshake() != 1) {
    throw errors::RuntimeException("Unable to perform client handshake");
  } else {
    TRANSPORT_LOGD("Handshake performed!");
  }

  initSessionSocket();

  if (tls_consumer_ == nullptr) {
    throw errors::RuntimeException("TLS socket does not exist");
  }

  std::shared_ptr<Name> prefix_name = std::make_shared<Name>(
      secure_prefix_.family,
      ip_address_get_buffer(&(secure_prefix_.address), secure_prefix_.family));
  std::shared_ptr<Prefix> prefix =
      std::make_shared<Prefix>(*prefix_name, secure_prefix_.len);

  if (payload_ != nullptr)
    return tls_consumer_->consume((prefix->mapName(name)), std::move(payload_));
  else
    return tls_consumer_->consume((prefix->mapName(name)));
}

int P2PSecureConsumerSocket::asyncConsume(const Name &name) {
  if (transport_protocol_->isRunning()) {
    return CONSUMER_BUSY;
  }

  if (handshake() != 1) {
    throw errors::RuntimeException("Unable to perform client handshake");
  } else {
    TRANSPORT_LOGD("Handshake performed!");
  }

  initSessionSocket();

  if (tls_consumer_ == nullptr) {
    throw errors::RuntimeException("TLS socket does not exist");
  }

  std::shared_ptr<Name> prefix_name = std::make_shared<Name>(
      secure_prefix_.family,
      ip_address_get_buffer(&(secure_prefix_.address), secure_prefix_.family));
  std::shared_ptr<Prefix> prefix =
      std::make_shared<Prefix>(*prefix_name, secure_prefix_.len);

  if (payload_ != NULL)
    return tls_consumer_->asyncConsume((prefix->mapName(name)),
                                       std::move(payload_));
  else
    return tls_consumer_->asyncConsume((prefix->mapName(name)));
}

void P2PSecureConsumerSocket::registerPrefix(const Prefix &producer_namespace) {
  producer_namespace_ = producer_namespace;
}

int P2PSecureConsumerSocket::setSocketOption(
    int socket_option_key, ReadCallback *socket_option_value) {
  return rescheduleOnIOService(
      socket_option_key, socket_option_value,
      [this](int socket_option_key, ReadCallback *socket_option_value) -> int {
        switch (socket_option_key) {
          case ConsumerCallbacksOptions::READ_CALLBACK:
            read_callback_decrypted_ = socket_option_value;
            break;
          default:
            return SOCKET_OPTION_NOT_SET;
        }

        return SOCKET_OPTION_SET;
      });
}

void P2PSecureConsumerSocket::getReadBuffer(uint8_t **application_buffer,
                                            size_t *max_length){};

void P2PSecureConsumerSocket::readDataAvailable(size_t length) noexcept {};

size_t P2PSecureConsumerSocket::maxBufferSize() const {
  return SSL3_RT_MAX_PLAIN_LENGTH;
}

void P2PSecureConsumerSocket::readBufferAvailable(
    std::unique_ptr<utils::MemBuf> &&buffer) noexcept {
  std::unique_lock<std::mutex> lck(this->mtx_);
  if (head_) {
    head_->prependChain(std::move(buffer));
  } else {
    head_ = std::move(buffer);
  }

  something_to_read_ = true;
  cv_.notify_one();
}

void P2PSecureConsumerSocket::readError(const std::error_code ec) noexcept {};

void P2PSecureConsumerSocket::readSuccess(std::size_t total_size) noexcept {
  std::unique_lock<std::mutex> lck(this->mtx_);
  content_downloaded_ = true;
  something_to_read_ = true;
  cv_.notify_one();
}

bool P2PSecureConsumerSocket::isBufferMovable() noexcept { return true; }

}  // namespace implementation
}  // namespace transport