/
rlm_radius_udp.c
2461 lines (2062 loc) · 69.9 KB
/
rlm_radius_udp.c
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
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This program is is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* 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 St, Fifth Floor, Boston, MA 02110-1301, USA
*/
/**
* $Id$
* @file rlm_radius_udp.c
* @brief RADIUS UDP transport
*
* @copyright 2017 Network RADIUS SARL
* @copyright 2020 Arran Cudbard-Bell (a.cudbardb@freeradius.org)
*/
RCSID("$Id$")
#include <freeradius-devel/io/application.h>
#include <freeradius-devel/io/listen.h>
#include <freeradius-devel/missing.h>
#include <freeradius-devel/server/connection.h>
#include <freeradius-devel/server/rad_assert.h>
#include <freeradius-devel/unlang/base.h>
#include <freeradius-devel/util/heap.h>
#include <freeradius-devel/util/udp.h>
#include <sys/socket.h>
#include "rlm_radius.h"
#include "track.h"
/** Static configuration for the module.
*
*/
typedef struct {
rlm_radius_t *parent; //!< rlm_radius instance.
CONF_SECTION *config;
fr_ipaddr_t dst_ipaddr; //!< IP of the home server.
fr_ipaddr_t src_ipaddr; //!< IP we open our socket on.
uint16_t dst_port; //!< Port of the home server.
char const *secret; //!< Shared secret.
char const *interface; //!< Interface to bind to.
uint32_t recv_buff; //!< How big the kernel's receive buffer should be.
uint32_t send_buff; //!< How big the kernel's send buffer should be.
uint32_t max_packet_size; //!< Maximum packet size.
uint16_t max_send_coalesce; //!< Maximum number of packets to coalesce into one mmsg call.
bool recv_buff_is_set; //!< Whether we were provided with a recv_buf
bool send_buff_is_set; //!< Whether we were provided with a send_buf
bool replicate; //!< Copied from parent->replicate
fr_trunk_conf_t *trunk_conf; //!< trunk configuration
} rlm_radius_udp_t;
typedef struct {
fr_event_list_t *el; //!< Event list.
rlm_radius_udp_t const *inst; //!< our instance
fr_trunk_t *trunk; //!< trunk handler
} udp_thread_t;
typedef struct {
fr_trunk_request_t *treq;
rlm_rcode_t rcode; //!< from the transport
} udp_result_t;
typedef struct udp_request_s udp_request_t;
typedef struct {
struct iovec out; //!< Describes buffer to send.
fr_trunk_request_t *treq; //!< Used for signalling.
} udp_coalesced_t;
/** Track the handle, which is tightly correlated with the FD
*
*/
typedef struct {
char const *name; //!< From IP PORT to IP PORT.
char const *module_name; //!< the module that opened the connection
int fd; //!< File descriptor.
struct mmsghdr *mmsgvec; //!< Vector of inbound/outbound packets.
udp_coalesced_t *coalesced; //!< Outbound coalesced requests.
rlm_radius_udp_t const *inst; //!< Our module instance.
udp_thread_t *thread;
uint8_t last_id; //!< Used when replicating to ensure IDs are distributed
///< evenly.
uint32_t max_packet_size; //!< Our max packet size. may be different from the parent.
fr_ipaddr_t src_ipaddr; //!< Source IP address. May be altered on bind
//!< to be the actual IP address packets will be
//!< sent on. This is why we can't use the inst
//!< src_ipaddr field.
uint16_t src_port; //!< Source port specific to this connection.
uint8_t *buffer; //!< Receive buffer.
size_t buflen; //!< Receive buffer length.
radius_track_t *tt; //!< RADIUS ID tracking structure.
fr_time_t mrs_time; //!< Most recent sent time which had a reply.
fr_time_t last_reply; //!< When we last received a reply.
fr_time_t first_sent; //!< first time we sent a packet since going idle
fr_time_t last_sent; //!< last time we sent a packet.
fr_time_t last_idle; //!< last time we had nothing to do
fr_event_timer_t const *zombie_ev; //!< Zombie timeout.
bool status_checking; //!< whether we're doing status checks
udp_request_t *status_u; //!< for sending status check packets
udp_result_t *status_r; //!< for faking out status checks as real packets
REQUEST *status_request;
} udp_handle_t;
/** Connect REQUEST to local tracking structure
*
*/
struct udp_request_s {
uint32_t priority; //!< copied from request->async->priority
fr_time_t recv_time; //!< copied from request->async->recv_time
int num_replies; //!< number of reply packets, sent is in retry.count
bool synchronous; //!< cached from inst->parent->synchronous
bool require_ma; //!< saved from the original packet.
bool can_retransmit; //!< can we retransmit this packet?
bool status_check; //!< is this packet a status check?
VALUE_PAIR *extra; //!< VPs for debugging, like Proxy-State.
uint8_t code; //!< Packet code.
uint8_t id; //!< Last ID assigned to this packet.
uint8_t *packet; //!< Packet we write to the network.
size_t packet_len; //!< Length of the packet.
radius_track_entry_t *rr; //!< ID tracking, resend count, etc.
fr_event_timer_t const *ev; //!< timer for retransmissions
fr_retry_t retry; //!< retransmission timers
};
static const CONF_PARSER module_config[] = {
{ FR_CONF_OFFSET("ipaddr", FR_TYPE_COMBO_IP_ADDR, rlm_radius_udp_t, dst_ipaddr), },
{ FR_CONF_OFFSET("ipv4addr", FR_TYPE_IPV4_ADDR, rlm_radius_udp_t, dst_ipaddr) },
{ FR_CONF_OFFSET("ipv6addr", FR_TYPE_IPV6_ADDR, rlm_radius_udp_t, dst_ipaddr) },
{ FR_CONF_OFFSET("port", FR_TYPE_UINT16, rlm_radius_udp_t, dst_port) },
{ FR_CONF_OFFSET("secret", FR_TYPE_STRING | FR_TYPE_REQUIRED, rlm_radius_udp_t, secret) },
{ FR_CONF_OFFSET("interface", FR_TYPE_STRING, rlm_radius_udp_t, interface) },
{ FR_CONF_OFFSET_IS_SET("recv_buff", FR_TYPE_UINT32, rlm_radius_udp_t, recv_buff) },
{ FR_CONF_OFFSET_IS_SET("send_buff", FR_TYPE_UINT32, rlm_radius_udp_t, send_buff) },
{ FR_CONF_OFFSET("max_packet_size", FR_TYPE_UINT32, rlm_radius_udp_t, max_packet_size), .dflt = "4096" },
{ FR_CONF_OFFSET("max_send_coalesce", FR_TYPE_UINT16, rlm_radius_udp_t, max_send_coalesce), .dflt = "1024" },
{ FR_CONF_OFFSET("src_ipaddr", FR_TYPE_COMBO_IP_ADDR, rlm_radius_udp_t, src_ipaddr) },
{ FR_CONF_OFFSET("src_ipv4addr", FR_TYPE_IPV4_ADDR, rlm_radius_udp_t, src_ipaddr) },
{ FR_CONF_OFFSET("src_ipv6addr", FR_TYPE_IPV6_ADDR, rlm_radius_udp_t, src_ipaddr) },
CONF_PARSER_TERMINATOR
};
static fr_dict_t const *dict_radius;
extern fr_dict_autoload_t rlm_radius_udp_dict[];
fr_dict_autoload_t rlm_radius_udp_dict[] = {
{ .out = &dict_radius, .proto = "radius" },
{ NULL }
};
static fr_dict_attr_t const *attr_acct_delay_time;
static fr_dict_attr_t const *attr_error_cause;
static fr_dict_attr_t const *attr_event_timestamp;
static fr_dict_attr_t const *attr_extended_attribute_1;
static fr_dict_attr_t const *attr_message_authenticator;
static fr_dict_attr_t const *attr_nas_identifier;
static fr_dict_attr_t const *attr_original_packet_code;
static fr_dict_attr_t const *attr_proxy_state;
static fr_dict_attr_t const *attr_response_length;
static fr_dict_attr_t const *attr_user_password;
static fr_dict_attr_t const *attr_packet_type;
extern fr_dict_attr_autoload_t rlm_radius_udp_dict_attr[];
fr_dict_attr_autoload_t rlm_radius_udp_dict_attr[] = {
{ .out = &attr_acct_delay_time, .name = "Acct-Delay-Time", .type = FR_TYPE_UINT32, .dict = &dict_radius},
{ .out = &attr_error_cause, .name = "Error-Cause", .type = FR_TYPE_UINT32, .dict = &dict_radius },
{ .out = &attr_event_timestamp, .name = "Event-Timestamp", .type = FR_TYPE_DATE, .dict = &dict_radius},
{ .out = &attr_extended_attribute_1, .name = "Extended-Attribute-1", .type = FR_TYPE_EXTENDED, .dict = &dict_radius},
{ .out = &attr_message_authenticator, .name = "Message-Authenticator", .type = FR_TYPE_OCTETS, .dict = &dict_radius},
{ .out = &attr_nas_identifier, .name = "NAS-Identifier", .type = FR_TYPE_STRING, .dict = &dict_radius},
{ .out = &attr_original_packet_code, .name = "Original-Packet-Code", .type = FR_TYPE_UINT32, .dict = &dict_radius},
{ .out = &attr_proxy_state, .name = "Proxy-State", .type = FR_TYPE_OCTETS, .dict = &dict_radius},
{ .out = &attr_response_length, .name = "Response-Length", .type = FR_TYPE_UINT32, .dict = &dict_radius },
{ .out = &attr_user_password, .name = "User-Password", .type = FR_TYPE_STRING, .dict = &dict_radius},
{ .out = &attr_packet_type, .name = "Packet-Type", .type = FR_TYPE_UINT32, .dict = &dict_radius },
{ NULL }
};
/** If we get a reply, the request must come from one of a small
* number of packet types.
*/
static FR_CODE allowed_replies[FR_RADIUS_MAX_PACKET_CODE] = {
[FR_CODE_ACCESS_ACCEPT] = FR_CODE_ACCESS_REQUEST,
[FR_CODE_ACCESS_CHALLENGE] = FR_CODE_ACCESS_REQUEST,
[FR_CODE_ACCESS_REJECT] = FR_CODE_ACCESS_REQUEST,
[FR_CODE_ACCOUNTING_RESPONSE] = FR_CODE_ACCOUNTING_REQUEST,
[FR_CODE_COA_ACK] = FR_CODE_COA_REQUEST,
[FR_CODE_COA_NAK] = FR_CODE_COA_REQUEST,
[FR_CODE_DISCONNECT_ACK] = FR_CODE_DISCONNECT_REQUEST,
[FR_CODE_DISCONNECT_NAK] = FR_CODE_DISCONNECT_REQUEST,
};
/** Turn a reply code into a module rcode;
*
*/
static rlm_rcode_t radius_code_to_rcode[FR_RADIUS_MAX_PACKET_CODE] = {
[FR_CODE_ACCESS_ACCEPT] = RLM_MODULE_OK,
[FR_CODE_ACCESS_CHALLENGE] = RLM_MODULE_UPDATED,
[FR_CODE_ACCESS_REJECT] = RLM_MODULE_REJECT,
[FR_CODE_ACCOUNTING_RESPONSE] = RLM_MODULE_OK,
[FR_CODE_COA_ACK] = RLM_MODULE_OK,
[FR_CODE_COA_NAK] = RLM_MODULE_REJECT,
[FR_CODE_DISCONNECT_ACK] = RLM_MODULE_OK,
[FR_CODE_DISCONNECT_NAK] = RLM_MODULE_REJECT,
[FR_CODE_PROTOCOL_ERROR] = RLM_MODULE_HANDLED,
};
/** Reset a status_check packet, ready to re-use
*
*/
static void status_check_reset(udp_handle_t *h, udp_request_t *u)
{
rad_assert(u->status_check == true);
h->status_checking = false;
u->num_replies = 0; /* Reset */
u->retry.start = 0;
if (u->rr) (void) radius_track_delete(&u->rr); /* Not used for conn status check */
if (u->ev) (void) fr_event_timer_delete(&u->ev);
TALLOC_FREE(u->packet);
fr_pair_list_free(&u->extra);
}
/*
* Status-Server checks. Manually build the packet, and
* all of its associated glue.
*/
static void status_check_alloc(fr_event_list_t *el, udp_handle_t *h)
{
udp_request_t *u;
REQUEST *request;
rlm_radius_udp_t const *inst = h->inst;
vp_map_t *map;
u = talloc_zero(h, udp_request_t);
/*
* Status checks are prioritized over any other packet
*/
u->priority = ~(uint32_t) 0;
u->status_check = true;
/*
* Allocate outside of the free list.
* There appears to be an issue where
* the thread destructor runs too
* early, and frees the freelist's
* head before the module destructor
* runs.
*/
request = request_local_alloc(h);
request->async = talloc_zero(request, fr_async_t);
talloc_const_free(request->name);
request->name = talloc_strdup(request, h->module_name);
request->el = el;
request->packet = fr_radius_alloc(request, false);
request->reply = fr_radius_alloc(request, false);
/*
* Create the VPs, and ignore any errors
* creating them.
*/
for (map = inst->parent->status_check_map; map != NULL; map = map->next) {
/*
* Skip things which aren't attributes.
*/
if (!tmpl_is_attr(map->lhs)) continue;
/*
* Ignore internal attributes.
*/
if (map->lhs->tmpl_da->flags.internal) continue;
/*
* Ignore signalling attributes. They shouldn't exist.
*/
if ((map->lhs->tmpl_da == attr_proxy_state) ||
(map->lhs->tmpl_da == attr_message_authenticator)) continue;
/*
* Allow passwords only in Access-Request packets.
*/
if ((inst->parent->status_check != FR_CODE_ACCESS_REQUEST) &&
(map->lhs->tmpl_da == attr_user_password)) continue;
(void) map_to_request(request, map, map_to_vp, NULL);
}
/*
* Ensure that there's a NAS-Identifier, if one wasn't
* already added.
*/
if (!fr_pair_find_by_da(request->packet->vps, attr_nas_identifier, TAG_ANY)) {
VALUE_PAIR *vp;
MEM(pair_add_request(&vp, attr_nas_identifier) >= 0);
fr_pair_value_strcpy(vp, "status check - are you alive?");
}
/*
* Always add an Event-Timestamp, which will be the time
* at which the first packet is sent. Or for
* Status-Server, the time of the current packet.
*/
if (!fr_pair_find_by_da(request->packet->vps, attr_event_timestamp, TAG_ANY)) {
MEM(pair_add_request(NULL, attr_event_timestamp) >= 0);
}
DEBUG3("Status check packet will be %s", fr_packet_codes[u->code]);
log_request_pair_list(L_DBG_LVL_3, request, request->packet->vps, NULL);
/*
* Initialize the request IO ctx. Note that we don't set
* destructors.
*/
u->code = inst->parent->status_check;
request->packet->code = u->code;
MEM(h->status_r = talloc_zero(h, udp_result_t));
h->status_u = u;
h->status_request = request;
}
/** Initialise a new outbound connection
*
* @param[out] h_out Where to write the new file descriptor.
* @param[in] conn to initialise.
* @param[in] uctx A #udp_connection_t
*/
static fr_connection_state_t conn_init(void **h_out, fr_connection_t *conn, void *uctx)
{
int fd;
udp_handle_t *h;
udp_thread_t *thread = talloc_get_type_abort(uctx, udp_thread_t);
uint16_t i;
h = talloc_zero(conn, udp_handle_t);
if (!h) return FR_CONNECTION_STATE_FAILED;
h->thread = thread;
h->inst = thread->inst;
h->module_name = h->inst->parent->name;
h->src_ipaddr = h->inst->src_ipaddr;
h->src_port = 0;
h->max_packet_size = h->inst->max_packet_size;
h->last_idle = fr_time();
/*
* mmsgvec is pre-populated with pointers
* to the iovec structs in coalesced, so we
* just need to setup the iovec, and pass how
* many messages we want to send to sendmmsg.
*/
h->mmsgvec = talloc_zero_array(h, struct mmsghdr, h->inst->max_send_coalesce);
h->coalesced = talloc_zero_array(h, udp_coalesced_t, h->inst->max_send_coalesce);
for (i = 0; i < h->inst->max_send_coalesce; i++) {
h->mmsgvec[i].msg_hdr.msg_iov = &h->coalesced[i].out;
h->mmsgvec[i].msg_hdr.msg_iovlen = 1;
}
MEM(h->buffer = talloc_array(h, uint8_t, h->max_packet_size));
h->buflen = h->max_packet_size;
if (!h->inst->replicate) MEM(h->tt = radius_track_alloc(h));
/*
* Open the outgoing socket.
*/
fd = fr_socket_client_udp(&h->src_ipaddr, &h->src_port, &h->inst->dst_ipaddr, h->inst->dst_port, true);
if (fd < 0) {
PERROR("%s - Failed opening socket", h->module_name);
talloc_free(h);
return FR_CONNECTION_STATE_FAILED;
}
/*
* Set the connection name.
*/
h->name = fr_asprintf(h, "connecting proto udp local %pV port %u remote %pV port %u",
fr_box_ipaddr(h->src_ipaddr), h->src_port,
fr_box_ipaddr(h->inst->dst_ipaddr), h->inst->dst_port);
#ifdef SO_RCVBUF
if (h->inst->recv_buff_is_set) {
int opt;
opt = h->inst->recv_buff;
if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &opt, sizeof(int)) < 0) {
WARN("%s - Failed setting 'recv_buf': %s", h->module_name, fr_syserror(errno));
}
}
#endif
#ifdef SO_SNDBUF
if (h->inst->send_buff_is_set) {
int opt;
opt = h->inst->send_buff;
if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &opt, sizeof(int)) < 0) {
WARN("%s - Failed setting 'send_buf': %s", h->module_name, fr_syserror(errno));
}
}
#endif
h->fd = fd;
/*
* @todo - if all connections are down, then only allow
* one to be open. And, start Status-Server messages on
* that connection.
*
* @todo - connection negotiation via Status-Server.
* This requires different "signal on fd" functions.
*/
fr_connection_signal_on_fd(conn, fd);
*h_out = h;
// @todo - initialize the tracking memory, etc.
// i.e. histograms (or hyperloglog) of packets, so we can see
// which connections / home servers are fast / slow.
return FR_CONNECTION_STATE_CONNECTING;
}
/** Process notification that fd is open
*
*/
static fr_connection_state_t conn_open(fr_event_list_t *el, void *handle, UNUSED void *uctx)
{
udp_handle_t *h = talloc_get_type_abort(handle, udp_handle_t);
rlm_radius_udp_t const *inst = h->inst;
talloc_const_free(h->name);
h->name = fr_asprintf(h, "proto udp local %pV port %u remote %pV port %u",
fr_box_ipaddr(h->src_ipaddr), h->src_port,
fr_box_ipaddr(inst->dst_ipaddr), inst->dst_port);
DEBUG("%s - Connection open - %s", h->module_name, h->name);
/*
* Connection is "active" now. i.e. we prefer the newly
* opened connection for sending packets.
*/
if (h->inst->parent->status_check) status_check_alloc(el, h);
return FR_CONNECTION_STATE_CONNECTED;
}
/** Shutdown/close a file descriptor
*
*/
static void conn_close(fr_event_list_t *el, void *handle, UNUSED void *uctx)
{
udp_handle_t *h = talloc_get_type_abort(handle, udp_handle_t);
fr_event_fd_delete(el, h->fd, FR_EVENT_FILTER_IO);
if (shutdown(h->fd, SHUT_RDWR) < 0) {
DEBUG3("%s - Failed shutting down connection %s: %s",
h->module_name, h->name, fr_syserror(errno));
}
if (close(h->fd) < 0) {
DEBUG3("%s - Failed closing connection %s: %s",
h->module_name, h->name, fr_syserror(errno));
}
h->fd = -1;
DEBUG("%s - Connection closed - %s", h->module_name, h->name);
}
/** Connection failed
*
* @param[in] handle of connection that failed.
* @param[in] state the connection was in when it failed.
* @param[in] uctx UNUSED.
*/
static fr_connection_state_t conn_failed(void *handle, fr_connection_state_t state, UNUSED void *uctx)
{
switch (state) {
/*
* If the connection was connected when it failed,
* we need to handle any outstanding packets and
* timer events before reconnecting.
*/
case FR_CONNECTION_STATE_CONNECTED:
{
udp_handle_t *h = talloc_get_type_abort(handle, udp_handle_t); /* h only available if connected */
/*
* Reset the Status-Server checks.
*/
if (h->status_u && h->status_u->ev) (void) fr_event_timer_delete(&h->status_u->ev);
}
break;
default:
break;
}
return FR_CONNECTION_STATE_INIT;
}
static fr_connection_t *thread_conn_alloc(fr_trunk_connection_t *tconn, fr_event_list_t *el,
fr_connection_conf_t const *conf,
char const *log_prefix, void *uctx)
{
fr_connection_t *conn;
udp_thread_t *thread = talloc_get_type_abort(uctx, udp_thread_t);
conn = fr_connection_alloc(tconn, el,
&(fr_connection_funcs_t){
.init = conn_init,
.open = conn_open,
.close = conn_close,
.failed = conn_failed
},
conf,
log_prefix,
thread);
if (!conn) {
talloc_free(conn);
PERROR("%s - Failed allocating state handler for new connection", thread->inst->parent->name);
return NULL;
}
return conn;
}
/** Read and discard data
*
*/
static void conn_discard(UNUSED fr_event_list_t *el, int fd, UNUSED int flags, void *uctx)
{
fr_trunk_connection_t *tconn = talloc_get_type_abort(uctx, fr_trunk_connection_t);
uint8_t buffer[4096];
ssize_t slen;
while ((slen = read(fd, buffer, sizeof(buffer))) > 0);
if (slen < 0) {
switch (errno) {
case EBADF:
case ECONNRESET:
case ENOTCONN:
case ETIMEDOUT:
fr_trunk_connection_signal_reconnect(tconn, FR_CONNECTION_FAILED);
break;
default:
break;
}
}
}
/** Standard I/O read function
*
* Underlying FD in now readable, so call the trunk to read any pending requests
* from this connection.
*
* @param[in] el The event list signalling.
* @param[in] fd that's now readable.
* @param[in] flags describing the read event.
* @param[in] uctx The trunk connection handle (tconn).
*/
static void conn_readable(UNUSED fr_event_list_t *el, UNUSED int fd, UNUSED int flags, void *uctx)
{
fr_trunk_connection_t *tconn = talloc_get_type_abort(uctx, fr_trunk_connection_t);
fr_trunk_connection_signal_readable(tconn);
}
/** Standard I/O write function
*
* Underlying FD is now writable, so call the trunk to write any pending requests
* to this connection.
*
* @param[in] el The event list signalling.
* @param[in] fd that's now writable.
* @param[in] flags describing the write event.
* @param[in] uctx The trunk connection handle (tcon).
*/
static void conn_writable(UNUSED fr_event_list_t *el, UNUSED int fd, UNUSED int flags, void *uctx)
{
fr_trunk_connection_t *tconn = talloc_get_type_abort(uctx, fr_trunk_connection_t);
fr_trunk_connection_signal_writable(tconn);
}
/** Connection errored
*
* We were signalled by the event loop that a fatal error occurred on this connection.
*
* @param[in] el The event list signalling.
* @param[in] fd that errored.
* @param[in] flags El flags.
* @param[in] fd_errno The nature of the error.
* @param[in] uctx The trunk connection handle (tconn).
*/
static void conn_error(UNUSED fr_event_list_t *el, UNUSED int fd, UNUSED int flags, int fd_errno, void *uctx)
{
fr_trunk_connection_t *tconn = talloc_get_type_abort(uctx, fr_trunk_connection_t);
fr_connection_t *conn = tconn->conn;
udp_handle_t *h = talloc_get_type_abort(conn->h, udp_handle_t);
ERROR("%s - Connection %s failed - %s", h->module_name, h->name, fr_syserror(fd_errno));
fr_connection_signal_reconnect(conn, FR_CONNECTION_FAILED);
}
static void thread_conn_notify(fr_trunk_connection_t *tconn, fr_connection_t *conn,
fr_event_list_t *el,
fr_trunk_connection_event_t notify_on, UNUSED void *uctx)
{
udp_handle_t *h = talloc_get_type_abort(conn->h, udp_handle_t);
fr_event_fd_cb_t read_fn = NULL;
fr_event_fd_cb_t write_fn = NULL;
switch (notify_on) {
/*
* We may have sent multiple requests to the
* other end, so it might be sending us multiple
* replies. We want to drain the socket, instead
* of letting the packets sit in the UDP receive
* queue.
*/
case FR_TRUNK_CONN_EVENT_NONE:
read_fn = conn_discard;
break;
case FR_TRUNK_CONN_EVENT_READ:
read_fn = conn_readable;
break;
case FR_TRUNK_CONN_EVENT_WRITE:
write_fn = conn_writable;
break;
case FR_TRUNK_CONN_EVENT_BOTH:
read_fn = conn_readable;
write_fn = conn_writable;
break;
}
if (fr_event_fd_insert(h, el, h->fd,
read_fn,
write_fn,
conn_error,
tconn) < 0) {
PERROR("%s - Failed inserting FD event", h->module_name);
/*
* May free the connection!
*/
fr_trunk_connection_signal_reconnect(tconn, FR_CONNECTION_FAILED);
}
}
/** A special version of the trunk/event loop glue function which always discards incoming data
*
*/
static void thread_conn_notify_replicate(fr_trunk_connection_t *tconn, fr_connection_t *conn,
fr_event_list_t *el,
fr_trunk_connection_event_t notify_on, UNUSED void *uctx)
{
udp_handle_t *h = talloc_get_type_abort(conn->h, udp_handle_t);
fr_event_fd_cb_t read_fn = NULL;
fr_event_fd_cb_t write_fn = NULL;
switch (notify_on) {
case FR_TRUNK_CONN_EVENT_NONE:
read_fn = conn_discard;
write_fn = NULL;
break;
case FR_TRUNK_CONN_EVENT_READ:
read_fn = conn_discard;
break;
case FR_TRUNK_CONN_EVENT_BOTH:
case FR_TRUNK_CONN_EVENT_WRITE:
read_fn = conn_discard;
write_fn = conn_writable;
break;
}
if (fr_event_fd_insert(h, el, h->fd,
read_fn,
write_fn,
conn_error,
tconn) < 0) {
PERROR("%s - Failed inserting FD event", h->module_name);
/*
* May free the connection!
*/
fr_trunk_connection_signal_reconnect(tconn, FR_CONNECTION_FAILED);
}
}
/*
* Return negative numbers to put 'a' at the top of the heap.
* Return positive numbers to put 'b' at the top of the heap.
*
* We want the value with the lowest timestamp to be prioritized at
* the top of the heap.
*/
static int8_t request_prioritise(void const *one, void const *two)
{
udp_request_t const *a = one;
udp_request_t const *b = two;
int8_t rcode;
// @todo - prioritize packets if there's a state?
/*
* Prioritise status check packets
*/
rcode = (b->status_check - a->status_check);;
if (rcode != 0) return rcode;
/*
* Larger priority is more important.
*/
rcode = (a->priority < b->priority) - (a->priority > b->priority);
if (rcode != 0) return rcode;
/*
* Smaller timestamp (i.e. earlier) is more important.
*/
return (a->recv_time > b->recv_time) - (a->recv_time < b->recv_time);
}
/** Decode response packet data, extracting relevant information and validating the packet
*
* @param[in] ctx to allocate pairs in.
* @param[out] reply Pointer to head of pair list to add reply attributes to.
* @param[out] response_code The type of response packet.
* @param[in] request_authenticator from the original request.
* @param[in] data to decode.
* @param[in] data_len Length of input data.
* @return
* - DECODE_FAIL_NONE on success.
* - DECODE_FAIL_* on failure.
*/
static decode_fail_t decode(TALLOC_CTX *ctx, VALUE_PAIR **reply, uint8_t *response_code,
udp_handle_t *h, REQUEST *request, udp_request_t *u,
uint8_t const request_authenticator[static RADIUS_AUTH_VECTOR_LENGTH],
uint8_t *data, size_t data_len)
{
rlm_radius_udp_t const *inst = h->thread->inst;
size_t packet_len;
decode_fail_t reason;
uint8_t code;
uint8_t original[RADIUS_HEADER_LENGTH];
*response_code = 0; /* Initialise to keep the rest of the code happy */
packet_len = data_len;
if (!fr_radius_ok(data, &packet_len, inst->parent->max_attributes, false, &reason)) {
RWARN("Ignoring malformed packet");
return reason;
}
if (RDEBUG_ENABLED3) {
RDEBUG3("Read packet");
fr_log_hex(&default_log, L_DBG, __FILE__, __LINE__, data, packet_len, NULL);
}
original[0] = u->code;
original[1] = 0; /* not looked at by fr_radius_verify() */
original[2] = 0;
original[3] = RADIUS_HEADER_LENGTH; /* for debugging */
memcpy(original + RADIUS_AUTH_VECTOR_OFFSET, request_authenticator, RADIUS_AUTH_VECTOR_LENGTH);
if (fr_radius_verify(data, original,
(uint8_t const *) inst->secret, talloc_array_length(inst->secret) - 1) < 0) {
RPWDEBUG("Ignoring response with invalid signature");
return DECODE_FAIL_MA_INVALID;
}
code = data[0];
if (!code || (code >= FR_RADIUS_MAX_PACKET_CODE)) {
REDEBUG("Unknown reply code %d", code);
return DECODE_FAIL_UNKNOWN_PACKET_CODE;
}
/*
* Protocol error is allowed as a response to any
* packet code.
*/
if (code != FR_CODE_PROTOCOL_ERROR) {
if (!allowed_replies[code]) {
REDEBUG("%s packet received invalid reply code %s",
fr_packet_codes[u->code], fr_packet_codes[code]);
return DECODE_FAIL_UNKNOWN_PACKET_CODE;
}
if (allowed_replies[code] != (FR_CODE) u->code) {
REDEBUG("%s packet received invalid reply code %s",
fr_packet_codes[u->code], fr_packet_codes[code]);
return DECODE_FAIL_UNKNOWN_PACKET_CODE;
}
}
/*
* Decode the attributes, in the context of the reply.
* This only fails if the packet is strangely malformed,
* or if we run out of memory.
*/
if (fr_radius_decode(ctx, data, packet_len, original,
inst->secret, talloc_array_length(inst->secret) - 1, reply) < 0) {
REDEBUG("Failed decoding attributes for packet");
fr_pair_list_free(reply);
return DECODE_FAIL_UNKNOWN;
}
RDEBUG("Received %s ID %d length %ld reply packet on connection %s",
fr_packet_codes[code], code, packet_len, h->name);
log_request_pair_list(L_DBG_LVL_2, request, *reply, NULL);
*response_code = code;
/*
* Record the fact we've seen a response
*/
u->num_replies++;
/*
* Fixup retry times
*/
if (u->retry.start > h->mrs_time) h->mrs_time = u->retry.start;
return DECODE_FAIL_NONE;
}
static int encode(rlm_radius_udp_t const *inst, REQUEST *request, udp_request_t *u, uint8_t id)
{
ssize_t packet_len;
uint8_t *msg = NULL;
int message_authenticator = u->require_ma * (RADIUS_MESSAGE_AUTHENTICATOR_LENGTH + 2);
int proxy_state = 6;
rad_assert(inst->parent->allowed[u->code]);
/*
* Might have been sent and then given up on... free the
* raw data so we can re-encode it.
*/
if (u->packet) {
TALLOC_FREE(u->packet);
fr_pair_list_free(&u->extra);
}
/*
* Try to retransmit, unless there are special
* circumstances.
*/
u->can_retransmit = true;
/*
* This is essentially free, as this memory was
* pre-allocated as part of the treq.
*/
u->packet_len = inst->max_packet_size;
MEM(u->packet = talloc_array(u, uint8_t, u->packet_len));
/*
* All proxied Access-Request packets MUST have a
* Message-Authenticator, otherwise they're insecure.
* Same goes for Status-Server.
*
* And we set the authentication vector to a random
* number...
*/
switch (u->code) {
case FR_CODE_ACCESS_REQUEST:
case FR_CODE_STATUS_SERVER:
{
size_t i;
uint32_t hash, base;
message_authenticator = RADIUS_MESSAGE_AUTHENTICATOR_LENGTH + 2;
base = fr_rand();
for (i = 0; i < RADIUS_AUTH_VECTOR_LENGTH; i += sizeof(uint32_t)) {
hash = fr_rand() ^ base;
memcpy(u->packet + RADIUS_AUTH_VECTOR_OFFSET + i, &hash, sizeof(hash));
}
}
default:
break;
}
/*
* If we're sending a status check packet, update any
* necessary timestamps. Also, don't add Proxy-State, as
* we're originating the packet.
*/
if (u->status_check) {
VALUE_PAIR *vp;
proxy_state = 0;
vp = fr_pair_find_by_da(request->packet->vps, attr_event_timestamp, TAG_ANY);
if (vp) {
vp->vp_date = fr_time_to_unix_time(u->retry.updated);
}
u->can_retransmit = false;
}
/*
* We should have at mininum 64-byte packets, so don't
* bother doing run-time checks here.
*/
rad_assert(u->packet_len >= (size_t) (RADIUS_HEADER_LENGTH + proxy_state + message_authenticator));
/*
* Encode it, leaving room for Proxy-State and
* Message-Authenticator if necessary.
*/
packet_len = fr_radius_encode(u->packet, u->packet_len - (proxy_state + message_authenticator), NULL,
inst->secret, talloc_array_length(inst->secret) - 1,
u->code, id, request->packet->vps);
if (packet_len <= 0) return -1;
/*
* Add Proxy-State to the tail end of the packet unless we are
* originating the request.
*
* We need to add it here, and NOT in
* request->packet->vps, because multiple modules
* may be sending the packets at the same time.
*
* Note that the length check will always pass, due to
* the buflen manipulation done above.
*/
if (proxy_state && !inst->parent->originate) {
uint8_t *attr = u->packet + packet_len;
VALUE_PAIR *vp;
fr_cursor_t cursor;
int count = 0;
rad_assert((size_t) (packet_len + proxy_state) <= u->packet_len);