|
| 1 | +import ipaddress |
| 2 | +import logging |
| 3 | + |
| 4 | +from django.contrib.auth import get_user_model |
| 5 | + |
| 6 | +from .counters.exceptions import MaxQuotaReached |
| 7 | +from .radclient.client import RadClient |
| 8 | +from .utils import ( |
| 9 | + execute_counter_checks, |
| 10 | + get_group_checks, |
| 11 | + get_group_replies, |
| 12 | + load_model, |
| 13 | +) |
| 14 | + |
| 15 | +logger = logging.getLogger(__name__) |
| 16 | + |
| 17 | +RadiusAccounting = load_model("RadiusAccounting") |
| 18 | +RadiusGroupCheck = load_model("RadiusGroupCheck") |
| 19 | +RadiusGroupReply = load_model("RadiusGroupReply") |
| 20 | +RadiusGroup = load_model("RadiusGroup") |
| 21 | +Nas = load_model("Nas") |
| 22 | +User = get_user_model() |
| 23 | + |
| 24 | + |
| 25 | +class ChangeOfAuthorizationManager: |
| 26 | + """ |
| 27 | + Manages Change of Authorization (CoA) operations for RADIUS users. |
| 28 | + Handles counter checks, attribute retrieval, and communication with NAS. |
| 29 | + """ |
| 30 | + |
| 31 | + def get_radsecret_from_radacct(self, rad_acct): |
| 32 | + """ |
| 33 | + Get RADIUS secret for a given RadiusAccounting session. |
| 34 | + """ |
| 35 | + qs = Nas.objects.filter(organization_id=rad_acct.organization_id).only( |
| 36 | + "name", "secret" |
| 37 | + ) |
| 38 | + nas_ip_address = ipaddress.ip_address(rad_acct.nas_ip_address) |
| 39 | + for nas in qs.iterator(): |
| 40 | + try: |
| 41 | + if nas_ip_address in ipaddress.ip_network(nas.name): |
| 42 | + return nas.secret |
| 43 | + except ValueError: |
| 44 | + logger.warning( |
| 45 | + f'Failed to parse NAS IP network for "{nas.id}" object. Skipping!' |
| 46 | + ) |
| 47 | + |
| 48 | + def get_radius_attributes(self, user, old_group_id, new_group): |
| 49 | + """ |
| 50 | + Get RADIUS attributes for CoA operation including both checks and replies. |
| 51 | + Returns dict of attributes. |
| 52 | + """ |
| 53 | + attributes = {} |
| 54 | + old_group = ( |
| 55 | + RadiusGroup.objects.prefetch_related( |
| 56 | + "radiusgroupcheck_set", "radiusgroupreply_set" |
| 57 | + ) |
| 58 | + .filter(id=old_group_id) |
| 59 | + .first() |
| 60 | + ) |
| 61 | + |
| 62 | + # Include all RadiusGroupReplies for the new group |
| 63 | + group_replies = get_group_replies(new_group) |
| 64 | + if group_replies: |
| 65 | + for key, value in group_replies.items(): |
| 66 | + attributes[key] = value["value"] |
| 67 | + elif old_group: |
| 68 | + # We need to unset attributes set by the previous group |
| 69 | + old_group_replies = get_group_replies(old_group) |
| 70 | + for reply in old_group_replies: |
| 71 | + attributes[reply] = "" |
| 72 | + |
| 73 | + # Include replies from the RadiusGroupChecks for the new group |
| 74 | + group_checks = get_group_checks(new_group) |
| 75 | + if group_checks: |
| 76 | + check_results = execute_counter_checks(user, new_group, group_checks) |
| 77 | + for reply, value in check_results.items(): |
| 78 | + attributes[reply] = str(value) |
| 79 | + elif old_group: |
| 80 | + # We need to unset attributes set by the previous group |
| 81 | + old_group_checks = get_group_checks(old_group, counters_only=True) |
| 82 | + check_results = execute_counter_checks( |
| 83 | + user, old_group, old_group_checks, raise_quota_exceeded=False |
| 84 | + ) |
| 85 | + for reply_name in check_results.keys(): |
| 86 | + attributes[reply_name] = "" |
| 87 | + |
| 88 | + return attributes |
| 89 | + |
| 90 | + def perform_change_of_authorization(self, user_id, old_group_id, new_group_id): |
| 91 | + """ |
| 92 | + Perform Change of Authorization for a user's group change. |
| 93 | + """ |
| 94 | + try: |
| 95 | + user = User.objects.get(pk=user_id) |
| 96 | + except User.DoesNotExist: |
| 97 | + logger.warning( |
| 98 | + f'Failed to find user with "{user_id}" ID. Skipping CoA operation.' |
| 99 | + ) |
| 100 | + return |
| 101 | + try: |
| 102 | + new_rad_group = ( |
| 103 | + RadiusGroup.objects.prefetch_related( |
| 104 | + "radiusgroupcheck_set", "radiusgroupreply_set" |
| 105 | + ) |
| 106 | + .select_related("organization", "organization__radius_settings") |
| 107 | + .get(id=new_group_id) |
| 108 | + ) |
| 109 | + except RadiusGroup.DoesNotExist: |
| 110 | + logger.warning( |
| 111 | + f'Failed to find RadiusGroup with "{new_group_id}" ID.' |
| 112 | + " Skipping CoA operation." |
| 113 | + ) |
| 114 | + return |
| 115 | + org_radius_settings = new_rad_group.organization.radius_settings |
| 116 | + # The coa_enabled value is provided by a FallbackBooleanChoiceField on the |
| 117 | + # model instance and cannot be reliably evaluated inside queryset filters. |
| 118 | + # Evaluate it here on the resolved model instance instead of trying to |
| 119 | + # filter at the database level. |
| 120 | + if not org_radius_settings.coa_enabled: |
| 121 | + logger.info( |
| 122 | + f'CoA is disabled for "{new_rad_group.organization}" organization.' |
| 123 | + " Skipping CoA operation." |
| 124 | + ) |
| 125 | + return |
| 126 | + # Check if user has open RadiusAccounting sessions |
| 127 | + open_sessions = RadiusAccounting.objects.filter( |
| 128 | + username=user.username, |
| 129 | + organization_id=new_rad_group.organization_id, |
| 130 | + stop_time__isnull=True, |
| 131 | + ) |
| 132 | + if not open_sessions: |
| 133 | + logger.warning( |
| 134 | + f'The user "{user.username} <{user.email}>" does not have any open' |
| 135 | + " RadiusAccounting sessions. Skipping CoA operation." |
| 136 | + ) |
| 137 | + return |
| 138 | + attributes = {} |
| 139 | + func = "perform_change_of_authorization" |
| 140 | + operation = "CoA" |
| 141 | + try: |
| 142 | + new_group_attributes = self.get_radius_attributes( |
| 143 | + user, old_group_id, new_rad_group |
| 144 | + ) |
| 145 | + if not new_group_attributes: |
| 146 | + # No attributes to send, skip CoA operation |
| 147 | + logger.warning( |
| 148 | + f'No RADIUS attributes found for "{new_group_id}" RadiusGroup.' |
| 149 | + " Skipping CoA operation." |
| 150 | + ) |
| 151 | + return |
| 152 | + attributes.update(new_group_attributes) |
| 153 | + except MaxQuotaReached: |
| 154 | + func = "perform_disconnect" |
| 155 | + operation = "Disconnect" |
| 156 | + updated_sessions = [] |
| 157 | + for session in open_sessions: |
| 158 | + radsecret = self.get_radsecret_from_radacct(session) |
| 159 | + if not radsecret: |
| 160 | + logger.warning( |
| 161 | + f'Failed to find RADIUS secret for "{session.unique_id}"' |
| 162 | + " RadiusAccounting object. Skipping CoA operation" |
| 163 | + " for this session." |
| 164 | + ) |
| 165 | + continue |
| 166 | + attributes["User-Name"] = session.username |
| 167 | + client = RadClient( |
| 168 | + host=session.nas_ip_address, |
| 169 | + radsecret=radsecret, |
| 170 | + ) |
| 171 | + result = getattr(client, func)(attributes) |
| 172 | + if result is True: |
| 173 | + session.groupname = new_rad_group.name |
| 174 | + updated_sessions.append(session) |
| 175 | + else: |
| 176 | + logger.warning( |
| 177 | + f'Failed to perform {operation} for "{session.unique_id}"' |
| 178 | + f' RadiusAccounting object of "{user}" user' |
| 179 | + ) |
| 180 | + RadiusAccounting.objects.bulk_update(updated_sessions, fields=["groupname"]) |
| 181 | + |
| 182 | + |
| 183 | +coa_manager = ChangeOfAuthorizationManager() |
0 commit comments