File: gss_context.cc

package info (click to toggle)
pdns-recursor 5.3.4-2
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 11,116 kB
  • sloc: cpp: 109,672; javascript: 20,651; python: 5,657; sh: 5,114; makefile: 782; ansic: 582; xml: 37
file content (584 lines) | stat: -rw-r--r-- 16,627 bytes parent folder | download | duplicates (4)
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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
/*
 * This file is part of PowerDNS or dnsdist.
 * Copyright -- PowerDNS.COM B.V. and its contributors
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of version 2 of the GNU General Public License as
 * published by the Free Software Foundation.
 *
 * In addition, for the avoidance of any doubt, permission is granted to
 * link this program with OpenSSL and to (re)distribute the binaries
 * produced as the result of such linking.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "gss_context.hh"
#include "logger.hh"

#ifndef ENABLE_GSS_TSIG

std::tuple<size_t, size_t, size_t> GssContext::getCounts() { return std::tuple<size_t, size_t, size_t>(0, 0, 0); }
bool GssContext::supported() { return false; }
GssContext::GssContext() :
  d_error(GSS_CONTEXT_UNSUPPORTED), d_type(GSS_CONTEXT_NONE) {}
GssContext::GssContext(const DNSName& /* label */) :
  d_error(GSS_CONTEXT_UNSUPPORTED), d_type(GSS_CONTEXT_NONE) {}
void GssContext::setLocalPrincipal(const std::string& /* name */) {}
bool GssContext::getLocalPrincipal(std::string& /* name */) { return false; }
void GssContext::setPeerPrincipal(const std::string& /* name */) {}
bool GssContext::getPeerPrincipal(std::string& /* name */) { return false; }
void GssContext::generateLabel(const std::string& /* suffix */) {}
void GssContext::setLabel(const DNSName& /* label */) {}
bool GssContext::init(const std::string& /* input */, std::string& /* output */) { return false; }
bool GssContext::accept(const std::string& /* input */, std::string& /* output */) { return false; }
bool GssContext::destroy() { return false; }
bool GssContext::expired() { return false; }
bool GssContext::valid() { return false; }
bool GssContext::sign(const std::string& /* input */, std::string& /* output */) { return false; }
bool GssContext::verify(const std::string& /* input */, const std::string& /* signature */) { return false; }
GssContextError GssContext::getError() { return GSS_CONTEXT_UNSUPPORTED; }

#else

#include <unordered_map>

#include "lock.hh"

#define TSIG_GSS_EXPIRE_INTERVAL 60

class GssCredential : boost::noncopyable
{
public:
  GssCredential(const std::string& name, const gss_cred_usage_t usage) :
    d_nameS(name), d_usage(usage)
  {
    gss_buffer_desc buffer;

    if (!name.empty()) {
      buffer.length = name.size();
      buffer.value = const_cast<void*>(static_cast<const void*>(name.c_str()));
      OM_uint32 min;
      auto maj = gss_import_name(&min, &buffer, (gss_OID)GSS_KRB5_NT_PRINCIPAL_NAME, &d_name);
      if (maj != GSS_S_COMPLETE) {
        d_name = GSS_C_NO_NAME;
        d_valid = false;
        return;
      }
    }

    renew();
  };

  ~GssCredential()
  {
    OM_uint32 tmp_min __attribute__((unused));
    if (d_cred != GSS_C_NO_CREDENTIAL) {
      (void)gss_release_cred(&tmp_min, &d_cred);
    }
    if (d_name != GSS_C_NO_NAME) {
      (void)gss_release_name(&tmp_min, &d_name);
    }
  };

  bool expired() const
  {
    if (d_expires == -1) {
      return false;
    }
    return time(nullptr) > d_expires;
  }

  bool renew()
  {
    OM_uint32 time_rec, tmp_maj, tmp_min __attribute__((unused));
    tmp_maj = gss_acquire_cred(&tmp_min, d_name, GSS_C_INDEFINITE, GSS_C_NO_OID_SET, d_usage, &d_cred, nullptr, &time_rec);

    if (tmp_maj != GSS_S_COMPLETE) {
      d_valid = false;
      (void)gss_release_name(&tmp_min, &d_name);
      d_name = GSS_C_NO_NAME;
      return false;
    }

    d_valid = true;

    // We do not want forever, but a good time
    if (time_rec == GSS_C_INDEFINITE) {
      time_rec = 24 * 60 * 60;
    }
    d_expires = time(nullptr) + time_rec;

    return true;
  }

  bool valid()
  {
    return d_valid && !expired();
  }

  std::string d_nameS;
  gss_cred_usage_t d_usage;
  gss_name_t d_name{GSS_C_NO_NAME};
  gss_cred_id_t d_cred{GSS_C_NO_CREDENTIAL};
  time_t d_expires{time(nullptr) + 60}; // partly initialized will be cleaned up
  bool d_valid{false};
}; // GssCredential

static LockGuarded<std::unordered_map<std::string, std::shared_ptr<GssCredential>>> s_gss_accept_creds;
static LockGuarded<std::unordered_map<std::string, std::shared_ptr<GssCredential>>> s_gss_init_creds;

class GssSecContext : boost::noncopyable
{
public:
  GssSecContext(std::shared_ptr<GssCredential> cred)
  {
    if (!cred->valid()) {
      throw PDNSException("Invalid credential " + cred->d_nameS);
    }
    d_cred = std::move(cred);
  }

  ~GssSecContext()
  {
    OM_uint32 tmp_maj __attribute__((unused)), tmp_min __attribute__((unused));
    if (d_ctx != GSS_C_NO_CONTEXT) {
      tmp_maj = gss_delete_sec_context(&tmp_min, &d_ctx, GSS_C_NO_BUFFER);
    }
    if (d_peer_name != GSS_C_NO_NAME) {
      tmp_maj = gss_release_name(&tmp_min, &(d_peer_name));
    }
  }

  std::shared_ptr<GssCredential> d_cred;
  GssContextType d_type{GSS_CONTEXT_NONE};
  gss_ctx_id_t d_ctx{GSS_C_NO_CONTEXT};
  gss_name_t d_peer_name{GSS_C_NO_NAME};
  time_t d_expires{time(nullptr) + 60}; // partly initialized will be cleaned up

  enum
  {
    GssStateInitial,
    GssStateNegotiate,
    GssStateComplete,
    GssStateError
  } d_state{GssStateInitial};
}; // GssSecContext

static LockGuarded<std::unordered_map<DNSName, std::shared_ptr<GssSecContext>>> s_gss_sec_context;

template <typename T>
static void doExpire(T& m, time_t now)
{
  auto lock = m.lock();
  for (auto i = lock->begin(); i != lock->end();) {
    if (now > i->second->d_expires) {
      i = lock->erase(i);
    }
    else {
      ++i;
    }
  }
}

static void expire()
{
  static time_t s_last_expired;
  time_t now = time(nullptr);
  if (now - s_last_expired < TSIG_GSS_EXPIRE_INTERVAL) {
    return;
  }
  s_last_expired = now;
  doExpire(s_gss_init_creds, now);
  doExpire(s_gss_accept_creds, now);
  doExpire(s_gss_sec_context, now);
}

bool GssContext::supported() { return true; }

void GssContext::initialize()
{
  d_peerPrincipal = "";
  d_localPrincipal = "";
  d_error = GSS_CONTEXT_NO_ERROR;
  d_type = GSS_CONTEXT_NONE;
}

GssContext::GssContext()
{
  initialize();
  generateLabel("pdns.tsig.");
}

GssContext::GssContext(const DNSName& label)
{
  initialize();
  setLabel(label);
}

void GssContext::generateLabel(const std::string& suffix)
{
  std::ostringstream oss;
  oss << std::hex << time(nullptr) << "." << suffix;
  setLabel(DNSName(oss.str()));
}

void GssContext::setLabel(const DNSName& label)
{
  d_label = label;
  auto lock = s_gss_sec_context.lock();
  auto it = lock->find(d_label);
  if (it != lock->end()) {
    d_secctx = it->second;
    d_type = d_secctx->d_type;
  }
}

bool GssContext::expired()
{
  return (!d_secctx || (d_secctx->d_expires > -1 && d_secctx->d_expires < time(nullptr)));
}

bool GssContext::valid()
{
  return (d_secctx && !expired() && d_secctx->d_state == GssSecContext::GssStateComplete);
}

bool GssContext::init(const std::string& input, std::string& output)
{
  expire();

  OM_uint32 tmp_maj __attribute__((unused)), tmp_min __attribute__((unused));
  OM_uint32 maj, min;
  gss_buffer_desc recv_tok, send_tok, buffer;
  OM_uint32 flags;
  OM_uint32 expires;

  if (d_label.empty()) {
    d_error = GSS_CONTEXT_INVALID;
    return false;
  }

  d_type = GSS_CONTEXT_INIT;
  std::shared_ptr<GssCredential> cred;
  {
    auto lock = s_gss_init_creds.lock();
    auto it = lock->find(d_localPrincipal);
    if (it == lock->end()) {
      it = lock->emplace(d_localPrincipal, std::make_shared<GssCredential>(d_localPrincipal, GSS_C_INITIATE)).first;
    }
    cred = it->second;
  }

  // see if we can find a context in non-completed state
  if (d_secctx) {
    if (d_secctx->d_state != GssSecContext::GssStateNegotiate) {
      d_error = GSS_CONTEXT_INVALID;
      return false;
    }
  }
  else {
    // make context
    auto lock = s_gss_sec_context.lock();
    d_secctx = std::make_shared<GssSecContext>(cred);
    d_secctx->d_state = GssSecContext::GssStateNegotiate;
    d_secctx->d_type = d_type;
    (*lock)[d_label] = d_secctx;
  }

  recv_tok.length = input.size();
  recv_tok.value = const_cast<void*>(static_cast<const void*>(input.c_str()));

  if (!d_peerPrincipal.empty()) {
    buffer.value = const_cast<void*>(static_cast<const void*>(d_peerPrincipal.c_str()));
    buffer.length = d_peerPrincipal.size();
    maj = gss_import_name(&min, &buffer, (gss_OID)GSS_KRB5_NT_PRINCIPAL_NAME, &(d_secctx->d_peer_name));
    if (maj != GSS_S_COMPLETE) {
      processError("gss_import_name", maj, min);
      return false;
    }
  }

  maj = gss_init_sec_context(&min, cred->d_cred, &d_secctx->d_ctx, d_secctx->d_peer_name, GSS_C_NO_OID, GSS_C_MUTUAL_FLAG | GSS_C_REPLAY_FLAG, GSS_C_INDEFINITE, GSS_C_NO_CHANNEL_BINDINGS, &recv_tok, nullptr, &send_tok, &flags, &expires);

  if (send_tok.length > 0) {
    output.assign(static_cast<char*>(send_tok.value), send_tok.length);
    tmp_maj = gss_release_buffer(&tmp_min, &send_tok);
  }

  if (maj == GSS_S_COMPLETE) {
    // We do not want forever
    if (expires == GSS_C_INDEFINITE) {
      expires = 60;
    }
    d_secctx->d_expires = time(nullptr) + expires;
    d_secctx->d_state = GssSecContext::GssStateComplete;
    return true;
  }
  else if (maj != GSS_S_CONTINUE_NEEDED) {
    processError("gss_init_sec_context", maj, min);
  }

  return (maj == GSS_S_CONTINUE_NEEDED);
}

bool GssContext::accept(const std::string& input, std::string& output)
{
  expire();

  OM_uint32 tmp_maj __attribute__((unused)), tmp_min __attribute__((unused));
  OM_uint32 maj, min;
  gss_buffer_desc recv_tok, send_tok;
  OM_uint32 flags;
  OM_uint32 expires;

  if (d_label.empty()) {
    d_error = GSS_CONTEXT_INVALID;
    return false;
  }

  d_type = GSS_CONTEXT_ACCEPT;
  std::shared_ptr<GssCredential> cred;
  {
    auto lock = s_gss_accept_creds.lock();
    auto it = lock->find(d_localPrincipal);
    if (it == lock->end()) {
      it = lock->emplace(d_localPrincipal, std::make_shared<GssCredential>(d_localPrincipal, GSS_C_ACCEPT)).first;
    }
    cred = it->second;
  }

  // see if we can find a context in non-completed state
  if (d_secctx) {
    if (d_secctx->d_state != GssSecContext::GssStateNegotiate) {
      d_error = GSS_CONTEXT_INVALID;
      return false;
    }
  }
  else {
    // make context
    auto lock = s_gss_sec_context.lock();
    d_secctx = std::make_shared<GssSecContext>(cred);
    d_secctx->d_state = GssSecContext::GssStateNegotiate;
    d_secctx->d_type = d_type;
    (*lock)[d_label] = d_secctx;
  }

  recv_tok.length = input.size();
  recv_tok.value = const_cast<void*>(static_cast<const void*>(input.c_str()));

  maj = gss_accept_sec_context(&min, &d_secctx->d_ctx, cred->d_cred, &recv_tok, GSS_C_NO_CHANNEL_BINDINGS, &d_secctx->d_peer_name, nullptr, &send_tok, &flags, &expires, nullptr);

  if (send_tok.length > 0) {
    output.assign(static_cast<char*>(send_tok.value), send_tok.length);
    tmp_maj = gss_release_buffer(&tmp_min, &send_tok);
  }

  if (maj == GSS_S_COMPLETE) {
    // We do not want forever
    if (expires == GSS_C_INDEFINITE) {
      expires = 60;
    }
    d_secctx->d_expires = time(nullptr) + expires;
    d_secctx->d_state = GssSecContext::GssStateComplete;
    return true;
  }
  else if (maj != GSS_S_CONTINUE_NEEDED) {
    processError("gss_accept_sec_context", maj, min);
  }
  return (maj == GSS_S_CONTINUE_NEEDED);
};

bool GssContext::sign(const std::string& input, std::string& output)
{
  OM_uint32 tmp_maj __attribute__((unused)), tmp_min __attribute__((unused));
  OM_uint32 maj, min;

  gss_buffer_desc recv_tok = GSS_C_EMPTY_BUFFER;
  gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;

  recv_tok.length = input.size();
  recv_tok.value = const_cast<void*>(static_cast<const void*>(input.c_str()));

  maj = gss_get_mic(&min, d_secctx->d_ctx, GSS_C_QOP_DEFAULT, &recv_tok, &send_tok);

  if (send_tok.length > 0) {
    output.assign(static_cast<char*>(send_tok.value), send_tok.length);
    tmp_maj = gss_release_buffer(&tmp_min, &send_tok);
  }

  if (maj != GSS_S_COMPLETE) {
    processError("gss_get_mic", maj, min);
  }

  return (maj == GSS_S_COMPLETE);
}

bool GssContext::verify(const std::string& input, const std::string& signature)
{
  OM_uint32 maj, min;

  gss_buffer_desc recv_tok = GSS_C_EMPTY_BUFFER;
  gss_buffer_desc sign_tok = GSS_C_EMPTY_BUFFER;

  recv_tok.length = input.size();
  recv_tok.value = const_cast<void*>(static_cast<const void*>(input.c_str()));
  sign_tok.length = signature.size();
  sign_tok.value = const_cast<void*>(static_cast<const void*>(signature.c_str()));

  maj = gss_verify_mic(&min, d_secctx->d_ctx, &recv_tok, &sign_tok, nullptr);

  if (maj != GSS_S_COMPLETE) {
    processError("gss_get_mic", maj, min);
  }

  return (maj == GSS_S_COMPLETE);
}

bool GssContext::destroy()
{
  if (d_label.empty()) {
    return false;
  }
  auto lock = s_gss_sec_context.lock();
  return lock->erase(d_label) == 1;
}

void GssContext::setLocalPrincipal(const std::string& name)
{
  d_localPrincipal = name;
}

bool GssContext::getLocalPrincipal(std::string& name)
{
  name = d_localPrincipal;
  return name.size() > 0;
}

void GssContext::setPeerPrincipal(const std::string& name)
{
  d_peerPrincipal = name;
}

bool GssContext::getPeerPrincipal(std::string& name)
{
  gss_buffer_desc value;
  OM_uint32 maj, min;

  if (d_secctx->d_peer_name != GSS_C_NO_NAME) {
    maj = gss_display_name(&min, d_secctx->d_peer_name, &value, nullptr);
    if (maj == GSS_S_COMPLETE && value.length > 0) {
      name.assign(static_cast<char*>(value.value), value.length);
      maj = gss_release_buffer(&min, &value);
      return true;
    }
    else {
      return false;
    }
  }
  else {
    return false;
  }
}

std::tuple<size_t, size_t, size_t> GssContext::getCounts()
{
  return {s_gss_init_creds.lock()->size(), s_gss_accept_creds.lock()->size(), s_gss_sec_context.lock()->size()};
}

void GssContext::processError(const std::string& method, OM_uint32 maj, OM_uint32 min)
{
  OM_uint32 tmp_min;
  gss_buffer_desc msg;
  OM_uint32 msg_ctx;

  msg_ctx = 0;
  while (1) {
    ostringstream oss;
    if (gss_display_status(&tmp_min, maj, GSS_C_GSS_CODE, GSS_C_NULL_OID, &msg_ctx, &msg) == GSS_S_COMPLETE) {
      oss << method << ": " << msg.value;
    }
    else {
      oss << method << ": ?";
    }
    if (msg.length != 0) {
      gss_release_buffer(&tmp_min, &msg);
    }
    d_gss_errors.push_back(oss.str());
    if (!msg_ctx)
      break;
  }
  msg_ctx = 0;
  while (1) {
    ostringstream oss;
    if (gss_display_status(&tmp_min, min, GSS_C_MECH_CODE, GSS_C_NULL_OID, &msg_ctx, &msg) == GSS_S_COMPLETE) {
      oss << method << ": " << msg.value;
    }
    else {
      oss << method << ": ?";
    }
    if (msg.length != 0) {
      gss_release_buffer(&tmp_min, &msg);
    }
    d_gss_errors.push_back(oss.str());
    if (!msg_ctx)
      break;
  }
}

#endif

bool gss_add_signature(const DNSName& context, const std::string& message, std::string& mac)
{
  string tmp_mac;
  GssContext gssctx(context);
  if (!gssctx.valid()) {
    g_log << Logger::Error << "GSS context '" << context << "' is not valid" << endl;
    for (const string& error : gssctx.getErrorStrings()) {
      g_log << Logger::Error << "GSS error: " << error << endl;
      ;
    }
    return false;
  }

  if (!gssctx.sign(message, tmp_mac)) {
    g_log << Logger::Error << "Could not sign message using GSS context '" << context << "'" << endl;
    for (const string& error : gssctx.getErrorStrings()) {
      g_log << Logger::Error << "GSS error: " << error << endl;
      ;
    }
    return false;
  }
  mac = std::move(tmp_mac);
  return true;
}

bool gss_verify_signature(const DNSName& context, const std::string& message, const std::string& mac)
{
  GssContext gssctx(context);
  if (!gssctx.valid()) {
    g_log << Logger::Error << "GSS context '" << context << "' is not valid" << endl;
    for (const string& error : gssctx.getErrorStrings()) {
      g_log << Logger::Error << "GSS error: " << error << endl;
      ;
    }
    return false;
  }

  if (!gssctx.verify(message, mac)) {
    g_log << Logger::Error << "Could not verify message using GSS context '" << context << "'" << endl;
    for (const string& error : gssctx.getErrorStrings()) {
      g_log << Logger::Error << "GSS error: " << error << endl;
      ;
    }
    return false;
  }
  return true;
}