public IRadiusPacket HandlePacket(IRadiusPacket packet)
        {
            var config    = ConfigurationManager.AppSettings;
            var domain    = config.Get("Domain");
            var groupName = config.Get("AdGroupName");

            _log.Info($"Recived request with packet code {packet.Code}");
            if (packet.Code == PacketCode.AccessRequest)
            {
                var userName     = packet.GetAttribute <String>("User-Name");
                var userPassword = packet.GetAttribute <String>("User-Password");
                var userLogin    = ValidateCredentials(domain, userName, userPassword, userName, userName);
                var userInGroup  = IsUserInAdGroup(domain, userName, groupName, userName, userPassword);
                _log.Info($"User Login result ={userLogin} UserInGroup result = {userInGroup} for user {userName}");
                if (userInGroup && userLogin)
                {
                    var response = packet.CreateResponsePacket(PacketCode.AccessAccept);
                    response.AddAttribute("Acct-Interim-Interval", 60);
                    return(response);
                }

                return(packet.CreateResponsePacket(PacketCode.AccessReject));
            }

            _log.Info($"Cant handle request code {packet.Code}");

            throw new InvalidOperationException($"Can't handle other requests besides AccessRequests with code {PacketCode.AccessRequest}");
        }
Esempio n. 2
0
        public IRadiusPacket HandlePacket(IRadiusPacket packet)
        {
            if (packet.Code == PacketCode.AccountingRequest)
            {
                switch (packet.GetAttribute <AcctStatusType>("Acct-Status-Type"))
                {
                case AcctStatusType.Start:
                case AcctStatusType.Stop:
                case AcctStatusType.InterimUpdate:
                    return(packet.CreateResponsePacket(PacketCode.AccountingResponse));

                default:
                    break;
                }
            }
            else if (packet.Code == PacketCode.AccessRequest)
            {
                if (packet.GetAttribute <string>("User-Name") == UserName && packet.GetAttribute <string>("User-Password") == UserPassword)
                {
                    var response = packet.CreateResponsePacket(PacketCode.AccessAccept);
                    response.AddAttribute("Acct-Interim-Interval", 60);
                    return(response);
                }

                return(packet.CreateResponsePacket(PacketCode.AccessReject));
            }

            throw new InvalidOperationException("Couldnt handle request?!");
        }
Esempio n. 3
0
        public IRadiusPacket HandlePacket(IRadiusPacket packet)
        {
            // Simulate lag
            //Thread.Sleep(new Random().Next(100, 3000));


            if (packet.Authenticator != null)
            {
                Console.WriteLine($"Authenticator {packet.Authenticator.ToHexString()}");
            }
            if (packet.SharedSecret != null)
            {
                Console.WriteLine($"SharedSecret {packet.SharedSecret.ToHexString()}");
            }

            foreach (var att in packet.Attributes)
            {
                Console.WriteLine($"ATT : {att.Key} - {att.Value}");
            }

            var userName      = packet.GetAttribute <String>("User-Name");
            var password      = packet.GetAttribute <String>("User-Password");
            var chap_password = packet.GetAttribute <byte[]>("CHAP-Password");

            Console.WriteLine($"userName {userName} password : {password} chap-password : {chap_password?.ToHexString()}");

            if (packet.Code == PacketCode.AccountingRequest)
            {
                var acctStatusType = packet.GetAttribute <AcctStatusType>("Acct-Status-Type");
                if (acctStatusType == AcctStatusType.Start)
                {
                    return(packet.CreateResponsePacket(PacketCode.AccountingResponse));
                }

                if (acctStatusType == AcctStatusType.Stop)
                {
                    return(packet.CreateResponsePacket(PacketCode.AccountingResponse));
                }

                if (acctStatusType == AcctStatusType.InterimUpdate)
                {
                    return(packet.CreateResponsePacket(PacketCode.AccountingResponse));
                }
            }
            else if (packet.Code == PacketCode.AccessRequest)
            {
                if (packet.GetAttribute <String>("User-Name") == "*****@*****.**" && packet.GetAttribute <String>("User-Password") == "1234")
                {
                    var response = packet.CreateResponsePacket(PacketCode.AccessAccept);
                    response.AddAttribute("Acct-Interim-Interval", 60);
                    return(response);
                }
                return(packet.CreateResponsePacket(PacketCode.AccessReject));
            }

            throw new InvalidOperationException("Couldnt handle request?!");
        }
        private IRadiusPacket Authenticate(IRadiusPacket packet)
        {
            var msisdn = packet.GetAttribute <String>("Calling-Station-Id");

            if (!packet.Attributes.ContainsKey("3GPP-User-Location-Info"))
            {
                _log.Warn("Missing 3GPP-User-Location-Info in packet, ignoring");
                return(null);
            }
            var locationInfo = Utils.GetMccMncFrom3GPPLocationInfo(packet.GetAttribute <Byte[]>("3GPP-User-Location-Info"));

            _log.Debug($"Handling authentication packet for {msisdn} on network {locationInfo.locationType}:{locationInfo.mccmnc}");
            using (var db = _contextFactory.GetContext())
            {
                if (locationInfo.mccmnc == "99999")
                {
                    _log.Warn($"No location info for msisdn {msisdn} check m2m portal 3GPP-SGSN-Address: {packet.GetAttribute<IPAddress>("3GPP-SGSN-Address")}");
                    return(packet.CreateResponsePacket(PacketCode.AccessReject));
                }
                var result = db.Authenticate1(msisdn, "flexinets", msisdn, locationInfo.mccmnc).ToList();
                if (result.Count > 0 && result.First() == null)
                {
                    var response = packet.CreateResponsePacket(PacketCode.AccessAccept);
                    response.AddAttribute("Acct-Interim-Interval", 60);
                    return(response);
                }
                else
                {
                    try
                    {
                        var mccmnc  = Convert.ToInt32(locationInfo.mccmnc);
                        var network = db.Networks.SingleOrDefault(o => o.mccmnc == mccmnc);
                        var simcard = db.SimCards.SingleOrDefault(o => o.Msisdn == msisdn);

                        var sb = new StringBuilder();

                        sb.AppendLine($"Authentication failed for {msisdn} on network {mccmnc} ({network?.providername}, {network?.countryname})");
                        if (simcard.user_id == null)
                        {
                            sb.AppendLine("Sim card not mapped to a user");
                        }
                        else
                        {
                            sb.AppendLine($"User: {simcard.UserSetting.user.username}@{simcard.UserSetting.user.realm}, group: {simcard.UserSetting.user.directory.name}");
                        }
                        _log.Warn(sb.ToString().Trim()); // todo needs throttling to reduce unwanted spam
                    }
                    catch (Exception ex)
                    {
                        _log.Error("huh?", ex);
                    }

                    return(packet.CreateResponsePacket(PacketCode.AccessReject));
                }
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Authenticate user through proxy or locally
        /// </summary>
        /// <param name="packet"></param>
        /// <returns></returns>
        private IRadiusPacket AuthenticateUser(IRadiusPacket packet)
        {
            var usernamedomain = packet.GetAttribute <String>("User-Name").ToLowerInvariant();
            var packetPassword = packet.GetAttribute <String>("User-Password");

            var proxyresponse = _authProxy.ProxyAuthentication(usernamedomain, packetPassword);

            if (proxyresponse.HasValue)
            {
                _log.Info($"Got response from proxy for username {usernamedomain}");
                return(packet.CreateResponsePacket(proxyresponse.Value));
            }
            else
            {
                using (var db = _contextFactory.GetContext())
                {
                    var username = UsernameDomain.Parse(usernamedomain);
                    var userid   = _userAuthProvider.AuthenticateAsync(username.Username, username.Domain, packetPassword).Result;
                    if (userid.HasValue)
                    {
                        return(packet.CreateResponsePacket(PacketCode.AccessAccept));
                    }
                    else
                    {
                        var user = db.users.SingleOrDefault(o => o.username == username.Username && o.realm == username.Domain);
                        if (user == null)
                        {
                            _log.Warn($"Username {usernamedomain} not found");
                        }
                        else if (user.status != 1)
                        {
                            _log.Warn($"Username {usernamedomain} is not active, email: {user.email}");
                        }
                        else
                        {
                            _log.Warn($"Bad password for user {usernamedomain}, password is {packetPassword.Length} characters, email: {user.email}");
                        }

                        var location = packet.GetAttribute <String>("Ipass-Location-Description");
                        if (!String.IsNullOrEmpty(location))
                        {
                            _log.Warn($"iPass location description: {location}");
                        }

                        return(packet.CreateResponsePacket(PacketCode.AccessReject));
                    }
                }
            }
        }
Esempio n. 6
0
        public IRadiusPacket HandlePacket(IRadiusPacket packet)
        {
            if (packet.Code == PacketCode.AccessRequest)
            {
                if (packet.GetAttribute <String>("User-Password") == "arctangent")
                {
                    var responsepacket = packet.CreateResponsePacket(PacketCode.AccessAccept);
                    responsepacket.AddAttribute("Service-Type", 1);
                    responsepacket.AddAttribute("Login-Service", 0);
                    responsepacket.AddAttribute("Login-IP-Host", IPAddress.Parse("192.168.1.3"));
                    return(responsepacket);
                }
            }

            var sb = new StringBuilder();

            sb.AppendLine($"Packet dump for {packet.Identifier}:");
            foreach (var attribute in packet.Attributes)
            {
                attribute.Value.ForEach(o => sb.AppendLine($"{attribute.Key} : {o} [{o.GetType()}]"));
            }
            Console.WriteLine(sb.ToString());
            //Console.WriteLine(packet.GetAttribute<String>("3GPP-GGSN-MCC-MNC"));
            throw new InvalidOperationException("Couldnt handle request?!");
        }
        private IRadiusPacket Stop(IRadiusPacket packet)
        {
            var user                = UsernameDomain.Parse(packet.GetAttribute <String>("User-Name"));
            var msisdn              = packet.GetAttribute <String>("Calling-Station-Id");
            var acctSessionId       = packet.GetAttribute <String>("Acct-Session-Id");
            var acctStatusType      = "Stop"; // duuh
            var acctInputOctets     = packet.GetAttribute <UInt32>("Acct-Input-Octets");
            var acctOutputOctets    = packet.GetAttribute <UInt32>("Acct-Output-Octets");
            var acctSessionTime     = packet.GetAttribute <UInt32>("Acct-Session-Time");
            var acctTerminateCause  = packet.GetAttribute <UInt32>("Acct-Terminate-Cause"); // oh crap, guess i need values as well...
            var acctInputGigawords  = packet.GetAttribute <UInt32?>("Acct-Input-Gigawords");
            var acctOutputGigawords = packet.GetAttribute <UInt32?>("Acct-Output-Gigawords");

            _log.Debug($"Handling stop packet for {msisdn} with AcctSessionId {acctSessionId}");
            try
            {
                using (var db = _contextFactory.GetContext())
                {
                    db.AccountingStop(user.Username, user.Domain, msisdn, acctStatusType, acctSessionId, acctInputOctets, acctOutputOctets,
                                      (int)acctSessionTime, acctTerminateCause.ToString(), acctInputGigawords, acctOutputGigawords);
                }
            }
            catch (EntityCommandExecutionException ex)
            {
                if (ex.InnerException?.Message.Contains("duplicate") ?? false)
                {
                    _log.Warn($"Duplicate stop packet for AcctSessionId {acctSessionId}");
                }
                else
                {
                    throw;
                }
            }
            return(packet.CreateResponsePacket(PacketCode.AccountingResponse));
        }
        private IRadiusPacket Interim(IRadiusPacket packet)
        {
            var user                = UsernameDomain.Parse(packet.GetAttribute <String>("User-Name"));
            var msisdn              = packet.GetAttribute <String>("Calling-Station-Id");
            var acctSessionId       = packet.GetAttribute <String>("Acct-Session-Id");
            var acctStatusType      = "Alive"; // duuh
            var acctInputOctets     = packet.GetAttribute <UInt32>("Acct-Input-Octets");
            var acctOutputOctets    = packet.GetAttribute <UInt32>("Acct-Output-Octets");
            var acctSessionTime     = packet.GetAttribute <UInt32>("Acct-Session-Time");
            var acctInputGigawords  = packet.GetAttribute <UInt32?>("Acct-Input-Gigawords");
            var acctOutputGigawords = packet.GetAttribute <UInt32?>("Acct-Output-Gigawords");
            var nasIpAddress        = packet.GetAttribute <IPAddress>("NAS-IP-Address");
            var mccmnc              = Utils.GetMccMncFrom3GPPLocationInfo(packet.GetAttribute <Byte[]>("3GPP-User-Location-Info")).mccmnc;

            _log.Debug($"Handling interim packet for {msisdn} on {mccmnc} with AcctSessionId {acctSessionId}");
            using (var db = _contextFactory.GetContext())
            {
                db.AccountingInterim(user.Username, user.Domain, msisdn, acctStatusType, acctSessionId, acctInputOctets, acctOutputOctets,
                                     (int)acctSessionTime, acctInputGigawords, acctOutputGigawords);
            }

            Task.Factory.StartNew(() =>
            {
                if (CheckDisconnect(acctSessionId))
                {
                    _disconnector.DisconnectUserByMsisdn(msisdn);
                }
            }, TaskCreationOptions.LongRunning);

            return(packet.CreateResponsePacket(PacketCode.AccountingResponse));
        }
        private IRadiusPacket Start(IRadiusPacket packet)
        {
            var user           = UsernameDomain.Parse(packet.GetAttribute <String>("User-Name"));
            var msisdn         = packet.GetAttribute <String>("Calling-Station-Id");
            var acctSessionId  = packet.GetAttribute <String>("Acct-Session-Id");
            var acctStatusType = "Start";    // duuh
            var locationInfo   = Utils.GetMccMncFrom3GPPLocationInfo(packet.GetAttribute <Byte[]>("3GPP-User-Location-Info"));

            _log.Debug($"Handling start packet for {msisdn} with AcctSessionId {acctSessionId}");

            try
            {
                using (var db = _contextFactory.GetContext())
                {
                    db.AccountingStart(user.Username, user.Domain, msisdn, acctStatusType, acctSessionId, locationInfo.mccmnc);
                }

                Task.Factory.StartNew(() => _welcomeSender.CheckWelcomeSms(msisdn), TaskCreationOptions.LongRunning);
            }
            catch (EntityCommandExecutionException ex)
            {
                if (ex.InnerException?.Message.Contains("duplicate") ?? false)
                {
                    _log.Warn($"Duplicate start packet for AcctSessionId {acctSessionId}");
                }
                else
                {
                    throw;
                }
            }

            return(packet.CreateResponsePacket(PacketCode.AccountingResponse));
        }
        public IRadiusPacket HandlePacket(IRadiusPacket packet)
        {
            // Simulate lag
            //Thread.Sleep(new Random().Next(100, 3000));

            if (packet.Code == PacketCode.AccountingRequest)
            {
                var acctStatusType = packet.GetAttribute <AcctStatusType>("Acct-Status-Type");
                if (acctStatusType == AcctStatusType.Start)
                {
                    return(packet.CreateResponsePacket(PacketCode.AccountingResponse));
                }

                if (acctStatusType == AcctStatusType.Stop)
                {
                    return(packet.CreateResponsePacket(PacketCode.AccountingResponse));
                }

                if (acctStatusType == AcctStatusType.InterimUpdate)
                {
                    return(packet.CreateResponsePacket(PacketCode.AccountingResponse));
                }
            }
            else if (packet.Code == PacketCode.AccessRequest)
            {
                if (packet.GetAttribute <String>("User-Name") == "*****@*****.**" && packet.GetAttribute <String>("User-Password") == "1234")
                {
                    var response = packet.CreateResponsePacket(PacketCode.AccessAccept);
                    response.AddAttribute("Acct-Interim-Interval", 60);
                    return(response);
                }
                return(packet.CreateResponsePacket(PacketCode.AccessReject));
            }

            throw new InvalidOperationException("Couldnt handle request?!");
        }
Esempio n. 11
0
        /// <summary>
        /// Accounting
        /// </summary>
        /// <param name="packet"></param>
        /// <returns></returns>
        private IRadiusPacket HandleAccountingPacket(IRadiusPacket packet)
        {
            var acctStatusType = packet.GetAttribute <AcctStatusType>("Acct-Status-Type");

            if (acctStatusType == AcctStatusType.Start || acctStatusType == AcctStatusType.Stop)
            {
                var usernamedomain = UsernameDomain.Parse(packet.GetAttribute <String>("User-Name"));
                var nodeid         = GetUserNodeId(usernamedomain.Username, usernamedomain.Domain);
                _log.Info($"Handling {acctStatusType} packet for {usernamedomain}");
                try
                {
                    using (var db = _contextFactory.GetContext())
                    {
                        var entry = new radiatoraccounting
                        {
                            username          = usernamedomain.Username,
                            realm             = usernamedomain.Domain,
                            node_id           = nodeid,
                            ACCTSTATUSTYPE    = (packet.GetAttribute <AcctStatusType>("Acct-Status-Type")).ToString(),
                            ACCTINPUTOCTETS   = Convert.ToUInt32(packet.GetAttribute <UInt32?>("Acct-Input-Octets")),
                            ACCTOUTPUTOCTETS  = Convert.ToUInt32(packet.GetAttribute <UInt32?>("Acct-Output-Octets")),
                            ACCTSESSIONID     = packet.GetAttribute <String>("Acct-Session-Id"),
                            ACCTSESSIONTIME   = Convert.ToInt32(packet.GetAttribute <UInt32?>("Acct-Session-Time")),
                            NASIDENTIFIER     = packet.GetAttribute <String>("NAS-Identifier"),
                            NASPORT           = packet.GetAttribute <UInt32?>("NAS-Port"),
                            NASPORTTYPE       = packet.GetAttribute <UInt32?>("NAS-Port-Type").ToString(),
                            WISPrLocationName = packet.GetAttribute <String>("WISPr-Location-Name"),
                            temp = packet.GetAttribute <String>("Ipass-Location-Description"),
                            timestamp_datetime = packet.Attributes.ContainsKey("Timestamp") ? (DateTime?)DateTimeOffset.FromUnixTimeSeconds(packet.GetAttribute <Int32>("Timestamp")).UtcDateTime : DateTime.UtcNow
                        };
                        db.radiatoraccountings.Add(entry);
                        db.SaveChanges();
                    }
                }
                catch (DbUpdateConcurrencyException)
                {
                    _log.Info($"Duplicate {acctStatusType} request received");
                }
                catch (Exception ex)
                {
                    _log.Error("Something went wrong", ex);
                }

                if (acctStatusType == AcctStatusType.Start)
                {
                    try
                    {
                        using (var db = _contextFactory.GetContext())
                        {
                            db.radiatoronlines.Add(new radiatoronline
                            {
                                username           = usernamedomain.Username,
                                realm              = usernamedomain.Domain,
                                node_id            = nodeid,
                                ACCTSESSIONID      = packet.GetAttribute <String>("Acct-Session-Id"),
                                timestamp_datetime = packet.Attributes.ContainsKey("Timestamp") ? (DateTime?)DateTimeOffset.FromUnixTimeSeconds(packet.GetAttribute <Int32>("Timestamp")).UtcDateTime : DateTime.UtcNow,
                                NASIDENTIFIER      = packet.GetAttribute <String>("NAS-Identifier"),
                                NASPORT            = packet.GetAttribute <UInt32?>("NAS-Port"),
                                NASPORTTYPE        = packet.GetAttribute <UInt32?>("NAS-Port-Type").ToString(),
                                WISPrLocationName  = packet.GetAttribute <String>("Ipass-Location-Description")
                            });
                            db.SaveChanges();
                        }
                    }
                    catch (DbUpdateConcurrencyException)
                    {
                        _log.Info("Cannot insert duplicate in radiatoronline");
                    }
                }
                if (acctStatusType == AcctStatusType.Stop)
                {
                    try
                    {
                        using (var db = _contextFactory.GetContext())
                        {
                            var acctsessionid = packet.GetAttribute <String>("Acct-Session-Id");
                            var online        = db.radiatoronlines.SingleOrDefault(o => o.ACCTSESSIONID == acctsessionid);
                            if (online != null)
                            {
                                db.radiatoronlines.Remove(online);
                                db.SaveChanges();
                            }
                        }
                    }
                    catch (DbUpdateConcurrencyException)
                    {
                        _log.Info("Nothing to remove from online");
                    }
                }
            }
            return(packet.CreateResponsePacket(PacketCode.AccountingResponse));
        }