File: auth.cc

package info (click to toggle)
xorp 1.8.5-4
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 28,560 kB
  • ctags: 54,995
  • sloc: cpp: 397,204; sh: 17,490; ansic: 17,029; python: 7,643; lex: 1,632; yacc: 1,474; awk: 956; makefile: 251; perl: 217; sed: 33
file content (845 lines) | stat: -rw-r--r-- 20,589 bytes parent folder | download | duplicates (3)
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
// -*- c-basic-offset: 4; tab-width: 8; indent-tabs-mode: t -*-

// Copyright (c) 2001-2011 XORP, Inc and Others
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License, Version 2, June
// 1991 as published by the Free Software Foundation. Redistribution
// and/or modification of this program under the terms of any other
// version of the GNU General Public License is not permitted.
// 
// 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. For more details,
// see the GNU General Public License, Version 2, a copy of which can be
// found in the XORP LICENSE.gpl file.
// 
// XORP Inc, 2953 Bunker Hill Lane, Suite 204, Santa Clara, CA 95054, USA;
// http://xorp.net



#include "rip_module.h"

#include "libxorp/xorp.h"
#include "libxorp/xlog.h"
#include "libxorp/eventloop.hh"


#include <openssl/md5.h>

#include "constants.hh"
#include "auth.hh"


// ----------------------------------------------------------------------------
// AuthHandlerBase implementation

AuthHandlerBase::~AuthHandlerBase()
{
}

const string&
AuthHandlerBase::error() const
{
    return _err;
}

inline void
AuthHandlerBase::reset_error()
{
    if (_err.empty() == false)
	_err.erase();
}

inline void
AuthHandlerBase::set_error(const string& err)
{
    _err = err;
}

// ----------------------------------------------------------------------------
// NullAuthHandler implementation

const char*
NullAuthHandler::effective_name() const
{
    return auth_type_name();
}

const char*
NullAuthHandler::auth_type_name()
{
    return "none";
}

void
NullAuthHandler::reset()
{
}

uint32_t
NullAuthHandler::head_entries() const
{
    return 0;
}

uint32_t
NullAuthHandler::max_routing_entries() const
{
    return RIPv2_ROUTES_PER_PACKET;
}

bool
NullAuthHandler::authenticate_inbound(const uint8_t*		packet,
				      size_t			packet_bytes,
				      const uint8_t*&		entries_ptr,
				      uint32_t&			n_entries,
				      const IPv4&,
				      bool)
{
    entries_ptr = NULL;
    n_entries = 0;

    if (packet_bytes > RIPv2_MAX_PACKET_BYTES) {
	set_error(c_format("packet too large (%u bytes)",
			   XORP_UINT_CAST(packet_bytes)));
	return false;
    } else if (packet_bytes < RIPv2_MIN_PACKET_BYTES) {
	set_error(c_format("packet too small (%u bytes)",
			   XORP_UINT_CAST(packet_bytes)));
	return false;
    }

    size_t entry_bytes = packet_bytes - RipPacketHeader::size();
    if (entry_bytes % PacketRouteEntry<IPv4>::size()) {
	set_error(c_format("non-integral route entries (%u bytes)",
			    XORP_UINT_CAST(entry_bytes)));
	return false;
    }

    n_entries = entry_bytes / PacketRouteEntry<IPv4>::size();
    if (n_entries == 0) {
	return true;
    }

    entries_ptr = packet + RipPacketHeader::size();

    const PacketRouteEntry<IPv4> entry(entries_ptr);
    // Reject packet if first entry is authentication data
    if (entry.is_auth_entry()) {
	set_error(c_format("unexpected authentication data (type %d)",
			   entry.tag()));
	entries_ptr = NULL;
	n_entries = 0;
	return false;
    }

    reset_error();
    return true;
}

bool
NullAuthHandler::authenticate_outbound(RipPacket<IPv4>&	packet,
				       list<RipPacket<IPv4> *>& auth_packets,
				       size_t&		n_routes)
{
    // XXX: nothing to do so just create a single copy
    RipPacket<IPv4>* copy_packet = new RipPacket<IPv4>(packet);
    auth_packets.push_back(copy_packet);

    reset_error();

    n_routes = packet.data_bytes() - RipPacketHeader::size();
    n_routes /= PacketRouteEntry<IPv4>::size();

    return (true);
}


// ----------------------------------------------------------------------------
// Plaintext handler implementation

const char*
PlaintextAuthHandler::effective_name() const
{
    return auth_type_name();
}

const char*
PlaintextAuthHandler::auth_type_name()
{
    return "simple";
}

void
PlaintextAuthHandler::reset()
{
}

uint32_t
PlaintextAuthHandler::head_entries() const
{
    return 1;
}

uint32_t
PlaintextAuthHandler::max_routing_entries() const
{
    return RIPv2_ROUTES_PER_PACKET - 1;
}

bool
PlaintextAuthHandler::authenticate_inbound(const uint8_t*	packet,
					   size_t		packet_bytes,
					   const uint8_t*&	entries_ptr,
					   uint32_t&		n_entries,
					   const IPv4&,
					   bool)
{
    entries_ptr = NULL;
    n_entries = 0;

    if (packet_bytes > RIPv2_MAX_PACKET_BYTES) {
	set_error(c_format("packet too large (%u bytes)",
			   XORP_UINT_CAST(packet_bytes)));
	return false;
    }

    if (packet_bytes < RIPv2_MIN_AUTH_PACKET_BYTES) {
	set_error(c_format("packet too small (%u bytes)",
			   XORP_UINT_CAST(packet_bytes)));
	return false;
    }

    size_t entry_bytes = packet_bytes - RipPacketHeader::size();
    if (entry_bytes % PacketRouteEntry<IPv4>::size()) {
	set_error(c_format("non-integral route entries (%u bytes)",
			   XORP_UINT_CAST(entry_bytes)));
	return false;
    }

    const PlaintextPacketRouteEntry4 ppr(packet + RipPacketHeader::size());

    if (ppr.addr_family() != PlaintextPacketRouteEntry4::ADDR_FAMILY) {
	set_error("not an authenticated packet");
	return false;
    } else if (ppr.auth_type() != PlaintextPacketRouteEntry4::AUTH_TYPE) {
	set_error("not a plaintext authenticated packet");
	return false;
    }

    string passwd = ppr.password();
    if (passwd != key()) {
	set_error(c_format("wrong password \"%s\"", passwd.c_str()));
	return false;
    }

    reset_error();
    n_entries = entry_bytes / PacketRouteEntry<IPv4>::size() - 1;
    if (n_entries) {
	entries_ptr = (packet + RipPacketHeader::size()
		       + PlaintextPacketRouteEntry4::size());
    }

    return true;
}

bool
PlaintextAuthHandler::authenticate_outbound(RipPacket<IPv4>&	packet,
					    list<RipPacket<IPv4> *>& auth_packets,
					    size_t&		n_routes)
{
    uint8_t* first_entry_ptr = NULL;

    if (head_entries() > 0)
	first_entry_ptr = packet.route_entry_ptr(0);

    x_static_assert(PacketRouteEntry<IPv4>::SIZE == 20);
    x_static_assert(PlaintextPacketRouteEntry4::SIZE == 20);
    XLOG_ASSERT(packet.data_ptr() + RipPacketHeader::size()
		== first_entry_ptr);

    PlaintextPacketRouteEntry4Writer ppr(first_entry_ptr);
    ppr.initialize(key());

    // XXX: just create a single copy
    RipPacket<IPv4>* copy_packet = new RipPacket<IPv4>(packet);
    auth_packets.push_back(copy_packet);

    reset_error();

    n_routes = packet.data_bytes() - RipPacketHeader::size();
    n_routes /= PacketRouteEntry<IPv4>::size();
    n_routes--;		// XXX: exclude the first (authentication) entry

    return (true);
}

const string&
PlaintextAuthHandler::key() const
{
    return _key;
}

void
PlaintextAuthHandler::set_key(const string& plaintext_key)
{
    _key = string(plaintext_key, 0, 16);
}


// ----------------------------------------------------------------------------
// MD5AuthHandler::MD5Key implementation

MD5AuthHandler::MD5Key::MD5Key(uint8_t		key_id,
			       const string&	key,
			       const TimeVal&	start_timeval,
			       const TimeVal&	end_timeval,
			       XorpTimer	start_timer,
			       XorpTimer	stop_timer)
    : _id(key_id),
      _start_timeval(start_timeval),
      _end_timeval(end_timeval),
      _is_persistent(false),
      _o_seqno(0),
      _start_timer(start_timer),
      _stop_timer(stop_timer)
{
    string::size_type n = key.copy(_key_data, 16);
    if (n < KEY_BYTES) {
	memset(_key_data + n, 0, KEY_BYTES - n);
    }
}

string
MD5AuthHandler::MD5Key::key() const
{
    return string(_key_data, 0, 16);
}

bool
MD5AuthHandler::MD5Key::valid_at(const TimeVal& when) const
{
    if (is_persistent())
	return true;

    return ((_start_timeval <= when) && (when <= _end_timeval));
}

void
MD5AuthHandler::MD5Key::reset()
{
    //
    // Reset the seqno
    //
    _lr_seqno.clear();

    //
    // Reset the flag that a packet has been received
    //
    _pkts_recv.clear();
}

void
MD5AuthHandler::MD5Key::reset(const IPv4& src_addr)
{
    map<IPv4, uint32_t>::iterator seqno_iter;
    map<IPv4, bool>::iterator recv_iter;

    //
    // Reset the seqno
    //
    seqno_iter = _lr_seqno.find(src_addr);
    if (seqno_iter != _lr_seqno.end())
	_lr_seqno.erase(seqno_iter);

    //
    // Reset the flag that a packet has been received
    //
    recv_iter = _pkts_recv.find(src_addr);
    if (recv_iter != _pkts_recv.end())
	_pkts_recv.erase(recv_iter);
}

bool
MD5AuthHandler::MD5Key::packets_received(const IPv4& src_addr) const
{
    map<IPv4, bool>::const_iterator iter;

    iter = _pkts_recv.find(src_addr);
    if (iter == _pkts_recv.end())
	return (false);

    return (iter->second);
}

uint32_t
MD5AuthHandler::MD5Key::last_seqno_recv(const IPv4& src_addr) const
{
    map<IPv4, uint32_t>::const_iterator iter;

    iter = _lr_seqno.find(src_addr);
    if (iter == _lr_seqno.end())
	return (0);

    return (iter->second);
}

void
MD5AuthHandler::MD5Key::set_last_seqno_recv(const IPv4& src_addr,
					    uint32_t seqno)
{
    map<IPv4, uint32_t>::iterator seqno_iter;
    map<IPv4, bool>::iterator recv_iter;

    //
    // Set the seqno
    //
    seqno_iter = _lr_seqno.find(src_addr);
    if (seqno_iter == _lr_seqno.end())
	_lr_seqno.insert(make_pair(src_addr, seqno));
    else
	seqno_iter->second = seqno;

    //
    // Set the flag that a packet has been received
    //
    recv_iter = _pkts_recv.find(src_addr);
    if (recv_iter == _pkts_recv.end())
	_pkts_recv.insert(make_pair(src_addr, true));
    else
	recv_iter->second = true;
}


// ----------------------------------------------------------------------------
// MD5AuthHandler implementation

MD5AuthHandler::MD5AuthHandler(EventLoop& eventloop)
    : _eventloop(eventloop)
{
}

const char*
MD5AuthHandler::effective_name() const
{
    //
    // XXX: if no valid keys, then don't use any authentication
    //
    if (_valid_key_chain.empty()) {
	return (_null_handler.effective_name());
    }

    return auth_type_name();
}

const char*
MD5AuthHandler::auth_type_name()
{
    return "md5";
}

void
MD5AuthHandler::reset()
{
    //
    // XXX: if no valid keys, then don't use any authentication
    //
    if (_valid_key_chain.empty()) {
	_null_handler.reset();
	return;
    }

    reset_keys();
}

uint32_t
MD5AuthHandler::head_entries() const
{
    //
    // XXX: if no valid keys, then don't use any authentication
    //
    if (_valid_key_chain.empty()) {
	return (_null_handler.head_entries());
    }

    return 1;
}

uint32_t
MD5AuthHandler::max_routing_entries() const
{
    //
    // XXX: if no valid keys, then don't use any authentication
    //
    if (_valid_key_chain.empty()) {
	return (_null_handler.max_routing_entries());
    }

    return RIPv2_ROUTES_PER_PACKET - 1;
}

bool
MD5AuthHandler::authenticate_inbound(const uint8_t*		packet,
				     size_t			packet_bytes,
				     const uint8_t*&		entries_ptr,
				     uint32_t&			n_entries,
				     const IPv4&		src_addr,
				     bool			new_peer)
{
    x_static_assert(MD5PacketTrailer::SIZE == 20);

    //
    // XXX: if no valid keys, then don't use any authentication
    //
    if (_valid_key_chain.empty()) {
	if (_null_handler.authenticate_inbound(packet, packet_bytes,
					       entries_ptr, n_entries,
					       src_addr, new_peer)
	    != true) {
	    set_error(_null_handler.error());
	    return (false);
	}
	reset_error();
	return (true);
    }

    entries_ptr = NULL;
    n_entries = 0;

    if (packet_bytes > RIPv2_MAX_PACKET_BYTES + MD5PacketTrailer::size()) {
	set_error(c_format("packet too large (%u bytes)",
			   XORP_UINT_CAST(packet_bytes)));
	return false;
    }

    if (packet_bytes < RIPv2_MIN_AUTH_PACKET_BYTES) {
	set_error(c_format("packet too small (%u bytes)",
			   XORP_UINT_CAST(packet_bytes)));
	return false;
    }

    const MD5PacketRouteEntry4 mpr(packet + RipPacketHeader::size());

    if (mpr.addr_family() != MD5PacketRouteEntry4::ADDR_FAMILY) {
	set_error("not an authenticated packet");
	return false;
    }

    if (mpr.auth_type() != MD5PacketRouteEntry4::AUTH_TYPE) {
	set_error("not an MD5 authenticated packet");
	return false;
    }

    if (mpr.auth_bytes() != MD5PacketTrailer::size()) {
	set_error(c_format("wrong number of auth bytes (%d != %u)",
			   mpr.auth_bytes(),
			   XORP_UINT_CAST(MD5PacketTrailer::size())));
	return false;
    }

    if (uint32_t(mpr.auth_off() + mpr.auth_bytes()) != packet_bytes) {
	set_error(c_format("Size of packet does not correspond with "
			   "authentication data offset and size "
			   "(%d + %d != %u).", mpr.auth_off(),
			   mpr.auth_bytes(),
			   XORP_UINT_CAST(packet_bytes)));
	return false;
    }

    KeyChain::iterator k = find_if(_valid_key_chain.begin(),
				   _valid_key_chain.end(),
				   bind2nd(mem_fun_ref(&MD5Key::id_matches),
					   mpr.key_id()));
    if (k == _valid_key_chain.end()) {
	set_error(c_format("packet with key ID %d for which no key is "
			   "configured", mpr.key_id()));
	return false;
    }
    MD5Key* key = &(*k);

    if (new_peer)
	key->reset(src_addr);

    uint32_t last_seqno_recv = key->last_seqno_recv(src_addr);
    if (key->packets_received(src_addr) && !(new_peer && mpr.seqno() == 0) &&
	(mpr.seqno() - last_seqno_recv >= 0x7fffffff)) {
	set_error(c_format("bad sequence number 0x%08x < 0x%08x",
			   XORP_UINT_CAST(mpr.seqno()),
			   XORP_UINT_CAST(last_seqno_recv)));
	return false;
    }

    const MD5PacketTrailer mpt(packet + mpr.auth_off());
    if (mpt.valid() == false) {
	set_error("invalid authentication trailer");
	return false;
    }

    MD5_CTX ctx;
    uint8_t digest[16];

    MD5_Init(&ctx);
    MD5_Update(&ctx, packet, mpr.auth_off() + mpt.auth_data_offset());
    MD5_Update(&ctx, key->key_data(), key->key_data_bytes());
    MD5_Final(digest, &ctx);

    if (memcmp(digest, mpt.auth_data(), mpt.auth_data_bytes()) != 0) {
	set_error(c_format("authentication digest doesn't match local key "
			   "(key ID = %d)", key->id()));
// #define	DUMP_BAD_MD5
#ifdef	DUMP_BAD_MD5
	const char badmd5[] = "/tmp/rip_badmd5";
	// If the file already exists don't dump anything. The file
	// should contain and only one packet.
	if (-1 == access(badmd5, R_OK)) {
	    XLOG_INFO("Dumping bad MD5 to %s", badmd5);
	    FILE *fp = fopen(badmd5, "w");
	    fwrite(packet, packet_bytes, 1 , fp);
	    fclose(fp);
	}
#endif
	return false;
    }

    // Update sequence number only after packet has passed digest check
    key->set_last_seqno_recv(src_addr, mpr.seqno());

    reset_error();
    n_entries = (mpr.auth_off() - RipPacketHeader::size()) /
	PacketRouteEntry<IPv4>::size() - 1;

    if (n_entries > 0) {
	entries_ptr = (packet + RipPacketHeader::size()
		       + MD5PacketRouteEntry4::size());
    }

    return true;
}

bool
MD5AuthHandler::authenticate_outbound(RipPacket<IPv4>&	packet,
				      list<RipPacket<IPv4> *>& auth_packets,
				      size_t&		n_routes)
{
    RipPacket<IPv4> first_packet(packet);
    vector<uint8_t> first_trailer;
    KeyChain::iterator iter;

    x_static_assert(MD5PacketTrailer::SIZE == 20);

    //
    // XXX: if no valid keys, then don't use any authentication
    //
    if (_valid_key_chain.empty()) {
	if (_null_handler.authenticate_outbound(packet, auth_packets,
						n_routes)
	    != true) {
	    set_error(_null_handler.error());
	    return (false);
	}
	reset_error();
	return (true);
    }

    //
    // Create an authenticated copy of the packet for each valid key
    //
    for (iter = _valid_key_chain.begin();
	 iter != _valid_key_chain.end();
	 ++iter) {
	MD5Key& key = *iter;

	RipPacket<IPv4>* copy_packet = new RipPacket<IPv4>(packet);
	auth_packets.push_back(copy_packet);

	uint8_t* first_entry_ptr = NULL;
	if (head_entries() > 0)
	    first_entry_ptr = copy_packet->route_entry_ptr(0);

	MD5PacketRouteEntry4Writer mpr(first_entry_ptr);

	mpr.initialize(copy_packet->data_bytes(), key.id(),
		       MD5PacketTrailer::size(),
		       key.next_seqno_out());

	vector<uint8_t> trailer;
	trailer.resize(MD5PacketTrailer::size());
	MD5PacketTrailerWriter mpt(&trailer[0]);
	mpt.initialize();

	MD5_CTX ctx;
	MD5_Init(&ctx);
	MD5_Update(&ctx, copy_packet->data_ptr(), mpr.auth_off());
	MD5_Update(&ctx, &trailer[0], mpt.auth_data_offset());
	MD5_Update(&ctx, key.key_data(), key.key_data_bytes());
	MD5_Final(mpt.auth_data(), &ctx);

	//
	// XXX: create a copy of the first packet without the trailer
	// and of the trailer itself.
	//
	if (iter == _valid_key_chain.begin()) {
	    first_packet = *copy_packet;
	    first_trailer = trailer;
	}

	copy_packet->append_data(trailer);
    }

    packet = first_packet;
    n_routes = packet.data_bytes() / MD5PacketRouteEntry4::size() - 1;
    packet.append_data(first_trailer);

    reset_error();

    return (true);
}

bool
MD5AuthHandler::add_key(uint8_t		key_id,
			const string&	key,
			const TimeVal&	start_timeval,
			const TimeVal&	end_timeval,
			string&		error_msg)
{
    TimeVal now;
    XorpTimer start_timer, end_timer;
    string dummy_error_msg;

    _eventloop.current_time(now);

    if (start_timeval > end_timeval) {
	error_msg = c_format("Start time is later than the end time");
	return false;
    }
    if (end_timeval < now) {
	error_msg = c_format("End time is in the past");
	return false;
    }

    if (start_timeval > now) {
	start_timer = _eventloop.new_oneoff_at(
	    start_timeval,
	    callback(this, &MD5AuthHandler::key_start_cb, key_id));
    }

    if (end_timeval != TimeVal::MAXIMUM()) {
	end_timer = _eventloop.new_oneoff_at(
	    end_timeval,
	    callback(this, &MD5AuthHandler::key_stop_cb, key_id));
    }

    //
    // XXX: If we are using the last authentication key that has expired,
    // move it to the list of invalid keys.
    //
    if (_valid_key_chain.size() == 1) {
	MD5Key& key = _valid_key_chain.front();
	if (key.is_persistent()) {
	    key.set_persistent(false);
	    _invalid_key_chain.push_back(key);
	    _valid_key_chain.pop_front();
	}
    }

    // XXX: for simplicity just try to remove the key even if it doesn't exist
    remove_key(key_id, dummy_error_msg);

    // Add the new key to the appropriate chain
    MD5Key new_key = MD5Key(key_id, key, start_timeval, end_timeval,
			    start_timer, end_timer);
    if (start_timer.scheduled())
	_invalid_key_chain.push_back(new_key);
    else
	_valid_key_chain.push_back(new_key);

    return true;
}

bool
MD5AuthHandler::remove_key(uint8_t key_id, string& error_msg)
{
    KeyChain::iterator i;

    // Check among all valid keys
    i = find_if(_valid_key_chain.begin(), _valid_key_chain.end(),
		bind2nd(mem_fun_ref(&MD5Key::id_matches), key_id));
    if (i != _valid_key_chain.end()) {
	_valid_key_chain.erase(i);
	return true;
    }

    // Check among all invalid keys
    i = find_if(_invalid_key_chain.begin(), _invalid_key_chain.end(),
		bind2nd(mem_fun_ref(&MD5Key::id_matches), key_id));
    if (i != _invalid_key_chain.end()) {
	_invalid_key_chain.erase(i);
	return true;
    }

    error_msg = c_format("No such key");
    return false;
}

void
MD5AuthHandler::key_start_cb(uint8_t key_id)
{
    KeyChain::iterator i;

    // Find the key among all invalid keys and move it to the valid keys
    i = find_if(_invalid_key_chain.begin(), _invalid_key_chain.end(),
		bind2nd(mem_fun_ref(&MD5Key::id_matches), key_id));
    if (i != _invalid_key_chain.end()) {
	MD5Key& key = *i;
	_valid_key_chain.push_back(key);
	_invalid_key_chain.erase(i);
    }
}

void
MD5AuthHandler::key_stop_cb(uint8_t key_id)
{
    KeyChain::iterator i;

    // Find the key among all valid keys and move it to the invalid keys
    i = find_if(_valid_key_chain.begin(), _valid_key_chain.end(),
		bind2nd(mem_fun_ref(&MD5Key::id_matches), key_id));
    if (i != _valid_key_chain.end()) {
	MD5Key& key = *i;
	//
	// XXX: If the last key expires then keep using it as per
	// RFC 2082 Section 4.3 until the lifetime is extended, the key
	// is deleted by network management, or a new key is configured.
	//
	if (_valid_key_chain.size() == 1) {
	    XLOG_WARNING("Last authentication key (key ID = %u) has expired. "
			 "Will keep using it until its lifetime is extended, "
			 "the key is deleted, or a new key is configured.",
			 key_id);
	    key.set_persistent(true);
	    return;
	}
	_invalid_key_chain.push_back(key);
	_valid_key_chain.erase(i);
    }
}

void
MD5AuthHandler::reset_keys()
{
    KeyChain::iterator iter;

    for (iter = _valid_key_chain.begin();
	 iter != _valid_key_chain.end();
	 ++iter) {
	iter->reset();
    }
}

bool
MD5AuthHandler::empty() const
{
    return (_valid_key_chain.empty() && _invalid_key_chain.empty());
}