aboutsummaryrefslogtreecommitdiffstats
path: root/libtransport/src/auth/signer.cc
blob: e74e2f1b82334c072102b67560f69cdb66c7cf49 (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
/*
 * Copyright (c) 2021 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 <glog/logging.h>
#include <hicn/transport/auth/signer.h>
#include <hicn/transport/utils/chrono_typedefs.h>

namespace transport {
namespace auth {

// ---------------------------------------------------------
// Base Signer
// ---------------------------------------------------------
Signer::Signer()
    : suite_(CryptoSuite::UNKNOWN), signature_len_(0), key_(nullptr) {}

Signer::~Signer() {}

void Signer::signPacket(PacketPtr packet) {
  DCHECK(key_ != nullptr);
  core::Packet::Format format = packet->getFormat();

  if (!packet->hasAH()) {
    throw errors::MalformedAHPacketException();
  }

  // Set signature size
  size_t signature_field_len = getSignatureFieldSize();
  packet->setSignatureFieldSize(signature_field_len);
  packet->updateLength();  // update IP payload length

  // Copy IP+TCP / ICMP header before zeroing them
  hicn_header_t header_copy;
  hicn_packet_copy_header(format, packet->packet_start_, &header_copy, false);

  // Fill in the hICN AH header
  auto now = utils::SteadyTime::nowMs().count();
  packet->setSignatureTimestamp(now);
  packet->setValidationAlgorithm(suite_);

  // Set key ID
  std::vector<uint8_t> key_id = key_id_.getDigest();
  packet->setKeyId({key_id.data(), key_id.size()});

  // Reset fields to compute the packet hash
  packet->resetForHash();

  // Compute the signature and put it in the packet
  signBuffer(packet);
  packet->setSignature(signature_);
  packet->setSignatureSize(signature_len_);

  // Restore header
  hicn_packet_copy_header(format, &header_copy, packet->packet_start_, false);
}

void Signer::signBuffer(const std::vector<uint8_t> &buffer) {
  DCHECK(key_ != nullptr);
  CryptoHashEVP hash_evp = CryptoHash::getEVP(getHashType());

  if (hash_evp == nullptr) {
    throw errors::RuntimeException("Unknown hash type");
  }

  std::shared_ptr<EVP_MD_CTX> mdctx(EVP_MD_CTX_create(), EVP_MD_CTX_free);

  if (mdctx == nullptr) {
    throw errors::RuntimeException("Digest context allocation failed");
  }

  if (EVP_DigestSignInit(mdctx.get(), nullptr, (*hash_evp)(), nullptr,
                         key_.get()) != 1) {
    throw errors::RuntimeException("Digest initialization failed");
  }

  if (EVP_DigestSignUpdate(mdctx.get(), buffer.data(), buffer.size()) != 1) {
    throw errors::RuntimeException("Digest update failed");
  }

  if (EVP_DigestSignFinal(mdctx.get(), nullptr, &signature_len_) != 1) {
    throw errors::RuntimeException("Digest computation failed");
  }

  signature_.resize(signature_len_);

  if (EVP_DigestSignFinal(mdctx.get(), signature_.data(), &signature_len_) !=
      1) {
    throw errors::RuntimeException("Digest computation failed");
  }

  signature_.resize(signature_len_);
}

void Signer::signBuffer(const utils::MemBuf *buffer) {
  DCHECK(key_ != nullptr);
  CryptoHashEVP hash_evp = CryptoHash::getEVP(getHashType());

  if (hash_evp == nullptr) {
    throw errors::RuntimeException("Unknown hash type");
  }

  const utils::MemBuf *p = buffer;
  std::shared_ptr<EVP_MD_CTX> mdctx(EVP_MD_CTX_create(), EVP_MD_CTX_free);

  if (mdctx == nullptr) {
    throw errors::RuntimeException("Digest context allocation failed");
  }

  if (EVP_DigestSignInit(mdctx.get(), nullptr, (*hash_evp)(), nullptr,
                         key_.get()) != 1) {
    throw errors::RuntimeException("Digest initialization failed");
  }

  do {
    if (EVP_DigestSignUpdate(mdctx.get(), p->data(), p->length()) != 1) {
      throw errors::RuntimeException("Digest update failed");
    }

    p = p->next();
  } while (p != buffer);

  if (EVP_DigestSignFinal(mdctx.get(), nullptr, &signature_len_) != 1) {
    throw errors::RuntimeException("Digest computation failed");
  }

  signature_.resize(signature_len_);

  if (EVP_DigestSignFinal(mdctx.get(), signature_.data(), &signature_len_) !=
      1) {
    throw errors::RuntimeException("Digest computation failed");
  }

  signature_.resize(signature_len_);
}

std::vector<uint8_t> Signer::getSignature() const { return signature_; }

std::string Signer::getStringSignature() const {
  std::stringstream string_sig;
  string_sig << std::hex << std::setfill('0');

  for (auto byte : signature_) {
    string_sig << std::hex << std::setw(2) << static_cast<int>(byte);
  }

  return string_sig.str();
}

size_t Signer::getSignatureSize() const { return signature_len_; }

size_t Signer::getSignatureFieldSize() const {
  if (signature_len_ % 4 == 0) {
    return signature_len_;
  }

  return (signature_len_ + 4) - (signature_len_ % 4);
}

CryptoSuite Signer::getSuite() const { return suite_; }

CryptoHashType Signer::getHashType() const {
  return ::transport::auth::getHashType(suite_);
}

void Signer::display() {
  std::cout << getStringSuite(suite_) << ": " << getStringSignature()
            << std::endl;
}

// ---------------------------------------------------------
// Void Signer
// ---------------------------------------------------------
void VoidSigner::signPacket(PacketPtr packet) {}

void VoidSigner::signBuffer(const std::vector<uint8_t> &buffer) {}

void VoidSigner::signBuffer(const utils::MemBuf *buffer) {}

// ---------------------------------------------------------
// Asymmetric Signer
// ---------------------------------------------------------
AsymmetricSigner::AsymmetricSigner(CryptoSuite suite,
                                   std::shared_ptr<EVP_PKEY> key,
                                   std::shared_ptr<EVP_PKEY> pub_key) {
  setKey(suite, key, pub_key);
}

AsymmetricSigner::AsymmetricSigner(std::string keystore_path,
                                   std::string password) {
  FILE *p12file = fopen(keystore_path.c_str(), "r");

  if (p12file == nullptr) {
    throw errors::RuntimeException("failed to read keystore");
  }

  std::unique_ptr<PKCS12, decltype(&PKCS12_free)> p12(
      d2i_PKCS12_fp(p12file, nullptr), &PKCS12_free);
  X509 *cert_raw;
  EVP_PKEY *key_raw;

  if (PKCS12_parse(p12.get(), password.c_str(), &key_raw, &cert_raw, nullptr) !=
      1) {
    fclose(p12file);
    throw errors::RuntimeException("failed to parse keystore");
  }

  std::shared_ptr<EVP_PKEY> key(key_raw, EVP_PKEY_free);
  std::shared_ptr<EVP_PKEY> pub_key(X509_get_pubkey(cert_raw), EVP_PKEY_free);

  setKey(transport::auth::getSuite(X509_get_signature_nid(cert_raw)), key,
         pub_key);

  fclose(p12file);
}

void AsymmetricSigner::setKey(CryptoSuite suite, std::shared_ptr<EVP_PKEY> key,
                              std::shared_ptr<EVP_PKEY> pub_key) {
  suite_ = suite;
  key_ = key;
  signature_len_ = EVP_PKEY_size(key.get());
  signature_.resize(signature_len_);

  std::vector<uint8_t> pbk(i2d_PublicKey(pub_key.get(), nullptr));
  uint8_t *pbk_ptr = pbk.data();
  int len = i2d_PublicKey(pub_key.get(), &pbk_ptr);

  key_id_ = CryptoHash(getHashType());
  key_id_.computeDigest(pbk_ptr, len);
}

size_t AsymmetricSigner::getSignatureFieldSize() const {
  size_t field_size = EVP_PKEY_size(key_.get());

  if (field_size % 4 == 0) {
    return field_size;
  }

  return (field_size + 4) - (field_size % 4);
}

// ---------------------------------------------------------
// Symmetric Signer
// ---------------------------------------------------------
SymmetricSigner::SymmetricSigner(CryptoSuite suite,
                                 const std::string &passphrase) {
  suite_ = suite;
  key_ = std::shared_ptr<EVP_PKEY>(
      EVP_PKEY_new_raw_private_key(EVP_PKEY_HMAC, nullptr,
                                   (const unsigned char *)passphrase.c_str(),
                                   passphrase.size()),
      EVP_PKEY_free);
  key_id_ = CryptoHash(getHashType());

  CryptoHashEVP hash_evp = CryptoHash::getEVP(getHashType());

  if (hash_evp == nullptr) {
    throw errors::RuntimeException("Unknown hash type");
  }

  signature_len_ = EVP_MD_size((*hash_evp)());
  signature_.resize(signature_len_);
  key_id_.computeDigest((uint8_t *)passphrase.c_str(), passphrase.size());
}

}  // namespace auth
}  // namespace transport