示例#1
0
        public void RadiusServer_Nas_HostRefresh()
        {
            // Verify that the server refreshes NAS host name to IP address mappings.
            // I'm going to do this by specifying a NAS host name that does not
            // exist, verify that an authentication fails, then add the host name
            // to the HOSTS file, wait a bit for the server to refresh the mappings
            // and then verify that this worked by making sure that an authentication
            // attempt succeeds.

            RadiusServer         server         = new RadiusServer();
            RadiusServerSettings serverSettings = new RadiusServerSettings();
            RadiusClient         client         = new RadiusClient();
            RadiusClientSettings clientSettings = new RadiusClientSettings(Local_RADIUS, "hello");

            serverSettings.RealmFormat        = RealmFormat.Email;
            serverSettings.DnsRefreshInterval = TimeSpan.FromSeconds(10);
            serverSettings.BkTaskInterval     = TimeSpan.FromSeconds(2);
            serverSettings.Devices.Add(new RadiusNasInfo("nas.test.lilltek.com", "hello"));

            clientSettings.RealmFormat      = RealmFormat.Email;
            clientSettings.PortCount        = 1;
            clientSettings.MaxTransmissions = 1;
            clientSettings.RetryInterval    = TimeSpan.FromSeconds(2);

            try
            {
                server.Start(serverSettings);
                server.LoadAccountsFromString(@"

    // This is a comment line

    r1;jeff;password123
    r2;jeff;passwordXXX
    r1;jane;bigfish
    ");

                client.Open(clientSettings);

                try
                {
                    client.Authenticate("r1", "jeff", "password123");
                    Assert.Fail();
                }
                catch (Exception e)
                {
                    Assert.IsInstanceOfType(e, typeof(TimeoutException));
                }

                EnhancedDns.AddHost("nas.test.lilltek.com", NetHelper.GetActiveAdapter());
                Thread.Sleep(serverSettings.DnsRefreshInterval + serverSettings.BkTaskInterval);

                Assert.IsTrue(client.Authenticate("r1", "jeff", "password123"));
            }
            finally
            {
                EnhancedDns.RemoveHosts();
                server.Stop();
                client.Close();
            }
        }
示例#2
0
        public void RadiusServer_Auth_Log()
        {
            // Verify that authentication events are logged

            RadiusServer         server         = new RadiusServer();
            RadiusServerSettings serverSettings = new RadiusServerSettings();
            RadiusClient         client         = new RadiusClient();
            RadiusClientSettings clientSettings = new RadiusClientSettings(Local_RADIUS, "hello");
            RadiusServerDeelie   deelie;

            serverSettings.RealmFormat = RealmFormat.Slash;
            serverSettings.Devices.Add(new RadiusNasInfo(IPAddress.Loopback, "hello"));
            serverSettings.Devices.Add(new RadiusNasInfo(NetHelper.GetActiveAdapter(), "hello"));

            clientSettings.RealmFormat      = RealmFormat.Slash;
            clientSettings.PortCount        = 1;
            clientSettings.MaxTransmissions = 1;

            try
            {
                server.Start(serverSettings);
                server.LoadAccountsFromString(@"

    // This is a comment line

    r1;jeff;password123
    r2;jeff;passwordXXX
    r1;jane;bigfish
    ");

                client.Open(clientSettings);
                deelie = new RadiusServerDeelie(server, RadiusServerDeelie.Mode.Normal);

                Assert.IsTrue(client.Authenticate("r1", "jeff", "password123"));
                Assert.IsFalse(client.Authenticate("r1", "jeff", "PASSWORD123"));

                Assert.AreEqual(2, deelie.Log.Count);

                Assert.IsTrue(deelie.Log[0].Success);
                Assert.AreEqual(RadiusLogEntryType.Authentication, deelie.Log[0].EntryType);
                Assert.AreEqual("r1", deelie.Log[0].Realm);
                Assert.AreEqual("jeff", deelie.Log[0].Account);

                Assert.IsFalse(deelie.Log[1].Success);
                Assert.AreEqual(RadiusLogEntryType.Authentication, deelie.Log[1].EntryType);
                Assert.AreEqual("r1", deelie.Log[1].Realm);
                Assert.AreEqual("jeff", deelie.Log[1].Account);
            }
            finally
            {
                server.Stop();
                client.Close();
            }
        }
示例#3
0
        /// <summary>
        /// Authenticates the account credentials against the authentication extension.
        /// </summary>
        /// <param name="realm">The authentication realm.</param>
        /// <param name="account">The account ID.</param>
        /// <param name="password">The password.</param>
        /// <returns>A <see cref="AuthenticationResult" /> instance with the result of the operation.</returns>
        /// <remarks>
        /// <para>
        /// The <see cref="AuthenticationResult.Status" /> property indicates the disposition
        /// of the authentication operation.  Extensions will return <see cref="AuthenticationStatus.Authenticated" />
        /// if the operation was successful.  Authentication failures due to the
        /// sumbission of invalid credentials will be indicated by returning one of
        /// the error codes.  Extensions may return specific error codes such as
        /// <see cref="AuthenticationStatus.BadPassword" /> and <see cref="AuthenticationStatus.BadAccount" />
        /// or the generic error code <see cref="AuthenticationStatus.AccessDenied" />.
        /// </para>
        /// <para>
        /// The <see cref="AuthenticationResult.MaxCacheTime" /> returns as the maximum time the
        /// results of the authentication operation should be cached.
        /// </para>
        /// </remarks>
        /// <exception cref="AuthenticationException">Thrown for authentication related exception.</exception>
        public AuthenticationResult Authenticate(string realm, string account, string password)
        {
            bool success;

            using (TimedLock.Lock(this))
            {
                if (!IsOpen)
                {
                    throw new AuthenticationException("Authentication extension is closed.");
                }

                try
                {
                    perf.Queries.Increment();
                    cAuthentications++;
                    success = radiusClient.Authenticate(realm, account, password);
                }
                catch (Exception e)
                {
                    perf.Exceptions.Increment();
                    throw new AuthenticationException(e);
                }

                if (success)
                {
                    return(new AuthenticationResult(AuthenticationStatus.Authenticated, maxCacheTime));
                }
                else
                {
                    return(new AuthenticationResult(AuthenticationStatus.AccessDenied, maxCacheTime));
                }
            }
        }
示例#4
0
        private async static Task Authenticate(string[] args)
        {
            RadiusClient rc         = new RadiusClient(args[0], args[1]);
            RadiusPacket authPacket = rc.Authenticate(args[2], args[3]);

            authPacket.SetAttribute(new VendorSpecificAttribute(10135, 1, UTF8Encoding.UTF8.GetBytes("Testing")));
            authPacket.SetAttribute(new VendorSpecificAttribute(10135, 2, new[] { (byte)7 }));
            RadiusPacket receivedPacket = await rc.SendAndReceivePacket(authPacket);

            if (receivedPacket == null)
            {
                throw new Exception("Can't contact remote radius server !");
            }
            switch (receivedPacket.PacketType)
            {
            case RadiusCode.ACCESS_ACCEPT:
                Console.WriteLine("Accepted");
                foreach (var attr in receivedPacket.Attributes)
                {
                    Console.WriteLine(attr.Type.ToString() + " = " + attr.Value);
                }
                break;

            case RadiusCode.ACCESS_CHALLENGE:
                Console.WriteLine("Challenged");
                break;

            default:
                Console.WriteLine("Rejected");
                break;
            }
        }
示例#5
0
        public void RadiusClient_Interop_AD_IAS()
        {
            if (EnvironmentVars.Get("LT_TESTBIN") == null)
            {
                Assert.Inconclusive("[LT_TESTBIN] environment variable does not exist.");
            }

            if (EnvironmentVars.Get("LT_TEST_AD") == null)
            {
                Assert.Inconclusive("[LT_TEST_AD] environment variable does not exist.");
            }

            var ad = new ADTestSettings();

            if (ad.NasSecret == string.Empty)
            {
                Assert.Inconclusive("AD/IAS Testing is disabled");
                return;
            }

            // Verify that RADIUS client works against AD/IAS.  This requires that
            // the LT_TEST_AD environment variable be set properly as described
            // in the LillTek DevInstall.doc document.  The IAS server must also
            // be manually configured with the NAS shared secret for this client.

            RadiusClient         client         = new RadiusClient();
            NetworkBinding       serverEP       = new NetworkBinding(EnhancedDns.GetHostByName(ad.Servers[0]).AddressList.IPv4Only()[0], NetworkPort.RADIUS);
            RadiusClientSettings clientSettings = new RadiusClientSettings(serverEP, ad.NasSecret);

            clientSettings.RealmFormat = RealmFormat.Email;
            clientSettings.PortCount   = 1;

            try
            {
                client.Open(clientSettings);

                Assert.IsTrue(client.Authenticate(ad.Domain, ad.Account, ad.Password));

                Assert.IsFalse(client.Authenticate(ad.Domain + "x", ad.Account, ad.Password));
                Assert.IsFalse(client.Authenticate(ad.Domain, ad.Account + "x", ad.Password));
                Assert.IsFalse(client.Authenticate(ad.Domain, ad.Account, ad.Password + "x"));
            }
            finally
            {
                client.Close();
            }
        }
示例#6
0
        public void RadiusClient_MultiPort()
        {
            // Verify that a multiport enable client actually works by running a bunch
            // of authentications throught the client and then counting the number of
            // source UDP ports we received packets from and verifying that this equals
            // the number of client ports requested.

            RadiusServer         server         = new RadiusServer();
            RadiusServerSettings serverSettings = new RadiusServerSettings();
            RadiusClient         client         = new RadiusClient();
            RadiusClientSettings clientSettings = new RadiusClientSettings(Local_RADIUS, "hello");
            RadiusServerDeelie   deelie;

            serverSettings.RealmFormat = RealmFormat.Email;
            serverSettings.Devices.Add(new RadiusNasInfo(IPAddress.Loopback, "hello"));
            serverSettings.Devices.Add(new RadiusNasInfo(NetHelper.GetActiveAdapter(), "hello"));

            clientSettings.RealmFormat      = RealmFormat.Email;
            clientSettings.PortCount        = 5;
            clientSettings.MaxTransmissions = 1;

            try
            {
                server.Start(serverSettings);
                server.LoadAccountsFromString(@"

    // This is a comment line

    r1;jeff;password123
    r2;jeff;passwordXXX
    r1;jane;bigfish
    ");

                client.Open(clientSettings);
                deelie = new RadiusServerDeelie(server, RadiusServerDeelie.Mode.Normal);

                for (int i = 0; i < 555; i++)
                {
                    Assert.IsTrue(client.Authenticate("r1", "jeff", "password123"));
                }

                Dictionary <int, RadiusPacket> packetsByPort = new Dictionary <int, RadiusPacket>();

                foreach (RadiusPacket packet in deelie.Packets)
                {
                    if (!packetsByPort.ContainsKey(packet.SourceEP.Port))
                    {
                        packetsByPort.Add(packet.SourceEP.Port, packet);
                    }
                }

                Assert.AreEqual(5, packetsByPort.Count);
            }
            finally
            {
                server.Stop();
                client.Close();
            }
        }
示例#7
0
        static int Main()
        {
            var username = Environment.GetEnvironmentVariable("username");
            var password = Environment.GetEnvironmentVariable("password");

            if (String.IsNullOrEmpty(username) || String.IsNullOrEmpty(password))
            {
                Console.WriteLine("environment variables username or password undefined");
                return(1);
            }

            if (Config.Settings == null)
            {
                Console.WriteLine("Config is empty/unreadable");
                return(1);
            }

            if (Config.Settings.Servers == null || Config.Settings.Servers.Count == 0)
            {
                Console.WriteLine("No servers found in config");
                return(1);
            }

            var res = Parallel.ForEach(Config.Settings.Servers.Cast <ServerElement>(), (server, state) =>
            {
                // Console.WriteLine("server.name = {0}, sharedsecret={1}, retries={2}, wait={3}, authport={4}", server.Name, server.sharedsecret, server.retries, server.wait, server.authport);

                var rc = new RadiusClient(server.Name, server.sharedsecret, server.wait * 1000, server.authport);
                try
                {
                    var authPacket = rc.Authenticate(username, password);
                    if (Config.Settings.NAS_IDENTIFIER != null)
                    {
                        authPacket.SetAttribute(new RadiusAttribute(RadiusAttributeType.NAS_IDENTIFIER, Encoding.ASCII.GetBytes(Config.Settings.NAS_IDENTIFIER)));
                    }

                    authPacket.SetAttribute(new RadiusAttribute(RadiusAttributeType.NAS_PORT_TYPE, BitConverter.GetBytes((int)NasPortType.ASYNC)));

                    var receivedPacket = rc.SendAndReceivePacket(authPacket, server.retries).Result;

                    if (receivedPacket != null && receivedPacket.PacketType == RadiusCode.ACCESS_ACCEPT)
                    {
                        state.Stop();
                    }
                }catch (Exception) {}
            });

            if (res.IsCompleted)
            {
                Console.WriteLine("Auth failed for: '{0}'", username);
                return(1);
            }
            else
            {
                Console.WriteLine("Auth Ok");
                return(0);
            }
        }
示例#8
0
        public void RadiusClient_Interop()
        {
            if (EnvironmentVars.Get("LT_TESTBIN") == null)
            {
                Assert.Inconclusive("[LT_TESTBIN] environment variable does not exist.");
            }

            // Verify that my RADIUS client code can work against a server from
            // another vendor.

            RadiusTestServer               server = new RadiusTestServer();
            Dictionary <string, string>    users;
            Dictionary <IPAddress, string> devices;
            RadiusClient         client         = new RadiusClient();
            RadiusClientSettings clientSettings = new RadiusClientSettings(Local_AAA, "secret");

            clientSettings.RealmFormat = RealmFormat.Email;
            clientSettings.PortCount   = 1;

            users = new Dictionary <string, string>();
            users.Add("jeff", "password1");
            users.Add("joe", "password2");

            devices = new Dictionary <IPAddress, string>();
            devices.Add(IPAddress.Loopback, "secret");
            devices.Add(NetHelper.GetActiveAdapter(), "secret");

            try
            {
                server.Start(users, devices);
                client.Open(clientSettings);

                Assert.IsTrue(client.Authenticate("", "jeff", "password1"));
                Assert.IsTrue(client.Authenticate("", "joe", "password2"));

                Assert.IsFalse(client.Authenticate("", "jeff", "passwordX"));
                Assert.IsFalse(client.Authenticate("", "billy", "x"));
            }
            finally
            {
                client.Close();
                server.Stop();
            }
        }
示例#9
0
        public void RadiusServer_Bad_Secret()
        {
            // Verify that the server detects a bad shared secret.

            RadiusServer         server         = new RadiusServer();
            RadiusServerSettings serverSettings = new RadiusServerSettings();
            RadiusClient         client         = new RadiusClient();
            RadiusClientSettings clientSettings = new RadiusClientSettings(Local_RADIUS, "hello");

            serverSettings.RealmFormat = RealmFormat.Slash;
            serverSettings.Devices.Add(new RadiusNasInfo(IPAddress.Loopback, "badsecret"));
            serverSettings.Devices.Add(new RadiusNasInfo(NetHelper.GetActiveAdapter(), "badsecret"));

            clientSettings.RealmFormat      = RealmFormat.Slash;
            clientSettings.PortCount        = 1;
            clientSettings.MaxTransmissions = 1;

            try
            {
                server.Start(serverSettings);
                server.LoadAccountsFromString(@"

    // This is a comment line

    r1;jeff;password123
    r2;jeff;passwordXXX
    r1;jane;bigfish
    ");

                client.Open(clientSettings);

                Assert.IsFalse(client.Authenticate("r1", "jeff", "password123"));
                Assert.IsFalse(client.Authenticate("r1", "jeff", "PASSWORD123"));
                Assert.IsFalse(client.Authenticate("", "jeff", "password123"));
                Assert.IsFalse(client.Authenticate(null, "jeff", "password123"));
                Assert.IsFalse(client.Authenticate("r3", "jeff", "password123"));
            }
            finally
            {
                server.Stop();
                client.Close();
            }
        }
示例#10
0
        public void RadiusServer_Bad_NasDevice()
        {
            // Verify that the server detects an unknown NAS device.

            RadiusServer         server         = new RadiusServer();
            RadiusServerSettings serverSettings = new RadiusServerSettings();
            RadiusClient         client         = new RadiusClient();
            RadiusClientSettings clientSettings = new RadiusClientSettings(Local_RADIUS, "hello");
            RadiusServerDeelie   deelie;

            serverSettings.RealmFormat = RealmFormat.Slash;

            clientSettings.RealmFormat      = RealmFormat.Slash;
            clientSettings.PortCount        = 1;
            clientSettings.MaxTransmissions = 1;

            try
            {
                server.Start(serverSettings);
                server.LoadAccountsFromString(@"

    // This is a comment line

    r1;jeff;password123
    r2;jeff;passwordXXX
    r1;jane;bigfish
    ");

                client.Open(clientSettings);
                deelie = new RadiusServerDeelie(server, RadiusServerDeelie.Mode.Normal);

                try
                {
                    client.Authenticate("r1", "jeff", "password123");
                    Assert.Fail("TimeoutException expected");
                }
                catch (TimeoutException)
                {
                    // Expecting a timeout since the server should ignore this packet
                }
                catch (Exception e)
                {
                    Assert.IsInstanceOfType(e, typeof(TimeoutException));
                }

                Assert.IsTrue(deelie.Log.Count > 0);
                Assert.AreEqual(RadiusLogEntryType.UnknownNas, deelie.Log[0].EntryType);
                Assert.IsFalse(deelie.Log[0].Success);
            }
            finally
            {
                server.Stop();
                client.Close();
            }
        }
示例#11
0
        public void RadiusClient_ID_WrapAround()
        {
            // Verify that a single port client instance will wrap request IDs
            // properly after ID=255

            RadiusServer         server         = new RadiusServer();
            RadiusServerSettings serverSettings = new RadiusServerSettings();
            RadiusClient         client         = new RadiusClient();
            RadiusClientSettings clientSettings = new RadiusClientSettings(Local_RADIUS, "hello");
            RadiusServerDeelie   deelie;

            serverSettings.RealmFormat = RealmFormat.Email;
            serverSettings.Devices.Add(new RadiusNasInfo(IPAddress.Loopback, "hello"));
            serverSettings.Devices.Add(new RadiusNasInfo(NetHelper.GetActiveAdapter(), "hello"));

            clientSettings.RealmFormat      = RealmFormat.Email;
            clientSettings.PortCount        = 1;
            clientSettings.MaxTransmissions = 1;

            try
            {
                server.Start(serverSettings);
                server.LoadAccountsFromString(@"

    // This is a comment line

    r1;jeff;password123
    r2;jeff;passwordXXX
    r1;jane;bigfish
    ");

                client.Open(clientSettings);
                deelie = new RadiusServerDeelie(server, RadiusServerDeelie.Mode.Normal);

                for (int i = 0; i < 555; i++)
                {
                    Assert.IsTrue(client.Authenticate("r1", "jeff", "password123"));
                }

                // We should have 555 packets in the deelie with ordered IDs.

                Assert.AreEqual(555, deelie.Packets.Count);
                for (int i = 0; i < 555; i++)
                {
                    Assert.AreEqual((byte)i, deelie.Packets[i].Identifier);
                }
            }
            finally
            {
                server.Stop();
                client.Close();
            }
        }
示例#12
0
        public void RadiusClient_Timeout()
        {
            // Verify that the client detects timeouts.

            RadiusServer         server         = new RadiusServer();
            RadiusServerSettings serverSettings = new RadiusServerSettings();
            RadiusClient         client         = new RadiusClient();
            RadiusClientSettings clientSettings = new RadiusClientSettings(Local_RADIUS, "hello");
            RadiusServerDeelie   deelie;

            serverSettings.RealmFormat = RealmFormat.Email;
            serverSettings.Devices.Add(new RadiusNasInfo(IPAddress.Loopback, "hello"));
            serverSettings.Devices.Add(new RadiusNasInfo(NetHelper.GetActiveAdapter(), "hello"));

            clientSettings.RealmFormat      = RealmFormat.Email;
            clientSettings.PortCount        = 1;
            clientSettings.MaxTransmissions = 1;

            try
            {
                server.Start(serverSettings);
                server.LoadAccountsFromString(@"

    // This is a comment line

    r1;jeff;password123
    r2;jeff;passwordXXX
    r1;jane;bigfish
    ");

                client.Open(clientSettings);
                deelie = new RadiusServerDeelie(server, RadiusServerDeelie.Mode.IgnoreAllPackets);

                try
                {
                    client.Authenticate("r1", "jeff", "password123");
                    Assert.Fail("Expected a timeout");
                }
                catch (Exception e)
                {
                    Assert.IsInstanceOfType(e, typeof(TimeoutException));
                }
            }
            finally
            {
                server.Stop();
                client.Close();
            }
        }
示例#13
0
        private static void Main(string[] args)
        {
            if (args.Length != 4)
            {
                ShowUsage();
                return;
            }

            try
            {
                RadiusClient rc         = new RadiusClient(args[0], args[1]);
                RadiusPacket authPacket = rc.Authenticate(args[2], args[3]);
                authPacket.SetAttribute(new VendorSpecificAttribute(10135, 1, UTF8Encoding.UTF8.GetBytes("Testing")));
                authPacket.SetAttribute(new VendorSpecificAttribute(10135, 2, new[] { (byte)7 }));
                RadiusPacket receivedPacket = rc.SendAndReceivePacket(authPacket).Result;
                if (receivedPacket == null)
                {
                    throw new Exception("Can't contact remote radius server !");
                }
                switch (receivedPacket.PacketType)
                {
                case RadiusCode.ACCESS_ACCEPT:
                    Console.WriteLine("Accepted");
                    foreach (var attr in receivedPacket.Attributes)
                    {
                        Console.WriteLine(attr.Type.ToString() + " = " + attr.Value);
                    }
                    break;

                case RadiusCode.ACCESS_CHALLENGE:
                    Console.WriteLine("Challenged");
                    break;

                default:
                    Console.WriteLine("Rejected");
                    break;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error : " + e.Message);
            }

            Console.ReadLine();
        }
示例#14
0
        private static void Main(string[] args)
        {
            if (args.Length != 4)
            {
                System.Console.WriteLine("Usage: TestClient hostName sharedSecret userName password");
                return;
            }

            String host   = args[0];
            String shared = args[1];
            String user   = args[2];
            String pass   = args[3];

            var rc = new RadiusClient(IPAddress.Parse(host), shared);

            // 1. Send Access-Request
            var ar = new AccessRequest(user, pass);

            ar.AuthProtocol = AuthenticationType.pap; // or AUTH_CHAP
            ar.AddAttribute("NAS-Identifier", "this.is.my.nas-identifier.de");
            ar.AddAttribute("NAS-IP-Address", "192.168.0.100");
            ar.AddAttribute("Service-Type", "Login-User");
            ar.AddAttribute("WISPr-Redirection-URL", "http://www.sourceforge.net/");
            ar.AddAttribute("WISPr-Location-ID", "net.sourceforge.ap1");

            System.Console.WriteLine("Packet before it is sent\n" + ar + "\n");
            RadiusPacket response = rc.Authenticate(ar);

            System.Console.WriteLine("Packet after it was sent\n" + ar + "\n");
            System.Console.WriteLine("Response\n" + response + "\n");

            // 2. Send Accounting-Request
            var acc = new AccountingRequest("mw", AccountingRequest.ACCT_STATUS_TYPE_START);

            acc.AddAttribute("Acct-Session-Id", "1234567890");
            acc.AddAttribute("NAS-Identifier", "this.is.my.nas-identifier.de");
            acc.AddAttribute("NAS-Port", "0");

            System.Console.WriteLine(acc + "\n");
            response = rc.Account(acc);
            System.Console.WriteLine("Response: " + response);

            rc.Close();
        }
示例#15
0
        private static int AuthRadius(string server, string secret, string userid, string password)
        {
            RadiusClient client = new RadiusClient();
            string       realm;
            string       account;
            int          pos;

            pos = userid.IndexOfAny(new char[] { '/', '\\' });
            if (pos == -1)
            {
                realm   = string.Empty;
                account = userid;
            }
            else
            {
                realm   = userid.Substring(0, pos);
                account = userid.Substring(pos + 1);
            }

            client.Open(new RadiusClientSettings(new NetworkBinding(server), secret));
            try
            {
                Program.Output("Authenticating...");
                if (client.Authenticate(realm, account, password))
                {
                    Program.Output("Success");
                    return(0);
                }
                else
                {
                    Program.Output("Failure");
                    return(1);
                }
            }
            catch (Exception e)
            {
                Program.Error("Error[{0}]: {1}", e.GetType().Name, e.Message);
                return(1);
            }
            finally
            {
                client.Close();
            }
        }
示例#16
0
        public void RadiusClient_Retry()
        {
            // Verify that the client actually retries sending request packets and
            // that it used the same ID for both.

            RadiusServer         server         = new RadiusServer();
            RadiusServerSettings serverSettings = new RadiusServerSettings();
            RadiusClient         client         = new RadiusClient();
            RadiusClientSettings clientSettings = new RadiusClientSettings(Local_RADIUS, "hello");
            RadiusServerDeelie   deelie;

            serverSettings.RealmFormat = RealmFormat.Email;
            serverSettings.Devices.Add(new RadiusNasInfo(IPAddress.Loopback, "hello"));
            serverSettings.Devices.Add(new RadiusNasInfo(NetHelper.GetActiveAdapter(), "hello"));

            clientSettings.RealmFormat      = RealmFormat.Email;
            clientSettings.PortCount        = 1;
            clientSettings.MaxTransmissions = 2;

            try
            {
                server.Start(serverSettings);
                server.LoadAccountsFromString(@"

    // This is a comment line

    r1;jeff;password123
    r2;jeff;passwordXXX
    r1;jane;bigfish
    ");

                client.Open(clientSettings);
                deelie = new RadiusServerDeelie(server, RadiusServerDeelie.Mode.IgnoreFirstPacket);

                Assert.IsTrue(client.Authenticate("r1", "jeff", "password123"));
                Assert.AreEqual(2, deelie.Packets.Count);
                Assert.AreEqual(deelie.Packets[0].Identifier, deelie.Packets[1].Identifier);
            }
            finally
            {
                server.Stop();
                client.Close();
            }
        }
示例#17
0
        public void RadiusServer_DefaultSecret()
        {
            // Verify that the default secret will be used if the NAS device
            // is not specified.

            RadiusServer         server         = new RadiusServer();
            RadiusServerSettings serverSettings = new RadiusServerSettings();
            RadiusClient         client         = new RadiusClient();
            RadiusClientSettings clientSettings = new RadiusClientSettings(Local_RADIUS, "hello");

            serverSettings.RealmFormat   = RealmFormat.Slash;
            serverSettings.DefaultSecret = "hello";

            clientSettings.RealmFormat      = RealmFormat.Slash;
            clientSettings.PortCount        = 1;
            clientSettings.MaxTransmissions = 1;

            try
            {
                server.Start(serverSettings);
                server.LoadAccountsFromString(@"

    // This is a comment line

    r1;jeff;password123
    r2;jeff;passwordXXX
    r1;jane;bigfish
    ");

                client.Open(clientSettings);

                Assert.IsTrue(client.Authenticate("r1", "jeff", "password123"));
                Assert.IsTrue(client.Authenticate("r2", "jeff", "passwordXXX"));
                Assert.IsTrue(client.Authenticate("r1", "jane", "bigfish"));

                Assert.IsFalse(client.Authenticate("r1", "jeff", "PASSWORD123"));
                Assert.IsFalse(client.Authenticate("", "jeff", "password123"));
                Assert.IsFalse(client.Authenticate(null, "jeff", "password123"));
                Assert.IsFalse(client.Authenticate("r3", "jeff", "password123"));
            }
            finally
            {
                server.Stop();
                client.Close();
            }
        }
示例#18
0
        public void RadiusServer_RealmFmt_Email()
        {
            // Test the client against the server using RealmFormat.Email.

            RadiusServer         server         = new RadiusServer();
            RadiusServerSettings serverSettings = new RadiusServerSettings();
            RadiusClient         client         = new RadiusClient();
            RadiusClientSettings clientSettings = new RadiusClientSettings(Local_RADIUS, "hello");

            serverSettings.RealmFormat = RealmFormat.Email;
            serverSettings.Devices.Add(new RadiusNasInfo(IPAddress.Loopback, "hello"));
            serverSettings.Devices.Add(new RadiusNasInfo(NetHelper.GetActiveAdapter(), "hello"));

            clientSettings.RealmFormat      = RealmFormat.Email;
            clientSettings.PortCount        = 1;
            clientSettings.MaxTransmissions = 1;

            try
            {
                server.Start(serverSettings);
                server.LoadAccountsFromString(@"

    // This is a comment line

    r1;jeff;password123
    r2;jeff;passwordXXX
    r1;jane;bigfish
    ");

                client.Open(clientSettings);

                Assert.IsTrue(client.Authenticate("r1", "jeff", "password123"));
                Assert.IsTrue(client.Authenticate("r2", "jeff", "passwordXXX"));
                Assert.IsTrue(client.Authenticate("r1", "jane", "bigfish"));

                Assert.IsFalse(client.Authenticate("r1", "jeff", "PASSWORD123"));
                Assert.IsFalse(client.Authenticate("", "jeff", "password123"));
                Assert.IsFalse(client.Authenticate(null, "jeff", "password123"));
                Assert.IsFalse(client.Authenticate("r3", "jeff", "password123"));
            }
            finally
            {
                server.Stop();
                client.Close();
            }
        }
示例#19
0
        public void RadiusServer_Nas_HostName()
        {
            // Verify that the server can handle NAS devices specified by DNS host name.

            RadiusServer         server         = new RadiusServer();
            RadiusServerSettings serverSettings = new RadiusServerSettings();
            RadiusClient         client         = new RadiusClient();
            RadiusClientSettings clientSettings = new RadiusClientSettings(Local_RADIUS, "hello");

            serverSettings.RealmFormat = RealmFormat.Email;
            serverSettings.Devices.Add(new RadiusNasInfo(Helper.MachineName, "hello"));

            clientSettings.RealmFormat      = RealmFormat.Email;
            clientSettings.PortCount        = 1;
            clientSettings.MaxTransmissions = 1;

            try
            {
                server.Start(serverSettings);
                server.LoadAccountsFromString(@"

    // This is a comment line

    r1;jeff;password123
    r2;jeff;passwordXXX
    r1;jane;bigfish
    ");

                client.Open(clientSettings);

                Assert.IsTrue(client.Authenticate("r1", "jeff", "password123"));
                Assert.IsTrue(client.Authenticate("r2", "jeff", "passwordXXX"));
                Assert.IsTrue(client.Authenticate("r1", "jane", "bigfish"));

                Assert.IsFalse(client.Authenticate("r1", "jeff", "PASSWORD123"));
                Assert.IsFalse(client.Authenticate("", "jeff", "password123"));
                Assert.IsFalse(client.Authenticate(null, "jeff", "password123"));
                Assert.IsFalse(client.Authenticate("r3", "jeff", "password123"));
            }
            finally
            {
                server.Stop();
                client.Close();
            }
        }
示例#20
0
        public static string AuthenticateRadius(string strHostName, uint nPort, string strSharedSecret, string strUserName, string strPassword, string strStateAttribut)
        {
            //strStateAttribut = "30-34-30-61-33-66-39-34-2D-65-39-39-36-2D-34-32-38-62-2D-38-32-65-63-2D-30-63-64-32-63-32-64-66-36-35-31-31";
            //strStateAttribut = "040a3f94-e996-428b-82ec-0cd2c2df6511";

            RadiusClient rc         = new RadiusClient(strHostName, strSharedSecret, authPort: nPort);
            RadiusPacket authPacket = rc.Authenticate(strUserName, strPassword);

            if (strStateAttribut != "")
            {
                //string buffer = String.Join("", strStateAttribut.Split('-'));
                byte[] data = Encoding.UTF8.GetBytes(strStateAttribut);

                authPacket.SetAttribute(new RadiusAttribute(RadiusAttributeType.STATE, data));
            }
            else
            {
                authPacket.SetAttribute(new VendorSpecificAttribute(10135, 1, UTF8Encoding.UTF8.GetBytes("Testing")));
                authPacket.SetAttribute(new VendorSpecificAttribute(10135, 2, new[] { (byte)7 }));
            }

            RadiusPacket receivedPacket = rc.SendAndReceivePacket(authPacket);

            if (receivedPacket == null)
            {
                throw new SmartException(9901, "Can't contact remote radius server !");
            }

            StringBuilder sbDebug  = new StringBuilder();
            StringBuilder sbRetour = new StringBuilder();

            switch (receivedPacket.PacketType)
            {
            case RadiusCode.ACCESS_ACCEPT:
                sbRetour.Append("2#");
                sbDebug.AppendLine("Access-Accept");
                foreach (var attr in receivedPacket.Attributes)
                {
                    sbDebug.AppendLine(attr.Type.ToString() + " = " + attr.Value);
                }
                break;

            case RadiusCode.ACCESS_CHALLENGE:
                sbRetour.Append("11#");
                sbDebug.AppendLine("Access-Challenge");
                foreach (var attr in receivedPacket.Attributes)
                {
                    sbDebug.AppendLine(attr.Type.ToString() + " = " + attr.Value);
                    if (attr.Type == RadiusAttributeType.STATE)
                    {
                        sbRetour.Append(attr.Value);
                    }
                }
                break;

            case RadiusCode.ACCESS_REJECT:
                sbRetour.Append("3#");
                sbDebug.AppendLine("Access-Reject");
                if (!rc.VerifyAuthenticator(authPacket, receivedPacket))
                {
                    sbDebug.AppendLine("Authenticator check failed: Check your secret");
                }
                break;

            default:
                sbRetour.Append("0#");
                sbDebug.AppendLine("Rejected");
                break;
            }

            //return sbDebug.ToString();
            return(sbRetour.ToString());
        }
示例#21
0
        public void RadiusClient_FailOver_MultiPort()
        {
            // Verify that the client actually fails over to alternate
            // RADIUS servers with a multi port client.

            RadiusServer         server1         = new RadiusServer();
            RadiusServer         server2         = new RadiusServer();
            RadiusServerSettings server1Settings = new RadiusServerSettings();
            RadiusServerSettings server2Settings = new RadiusServerSettings();
            RadiusClient         client          = new RadiusClient();
            RadiusClientSettings clientSettings  = new RadiusClientSettings(new NetworkBinding[] { Local_AAA, NetworkBinding.Parse("192.168.255.1:1645") }, "hello");
            RadiusServerDeelie   deelie1;
            RadiusServerDeelie   deelie2;

            server1Settings.RealmFormat = RealmFormat.Email;
            server1Settings.Devices.Add(new RadiusNasInfo(IPAddress.Loopback, "hello"));
            server1Settings.Devices.Add(new RadiusNasInfo(NetHelper.GetActiveAdapter(), "hello"));
            server1Settings.NetworkBinding = new IPEndPoint(IPAddress.Any, NetworkPort.RADIUS);

            server2Settings.RealmFormat = RealmFormat.Email;
            server2Settings.Devices.Add(new RadiusNasInfo(IPAddress.Loopback, "hello"));
            server2Settings.Devices.Add(new RadiusNasInfo(NetHelper.GetActiveAdapter(), "hello"));
            server2Settings.NetworkBinding = new IPEndPoint(IPAddress.Any, NetworkPort.AAA);

            clientSettings.RealmFormat      = RealmFormat.Email;
            clientSettings.PortCount        = 4;
            clientSettings.MaxTransmissions = 10;
            clientSettings.RetryInterval    = TimeSpan.FromSeconds(0.5);

            try
            {
                string accountInfo = @"

    // This is a comment line

    r1;jeff;password123
    r2;jeff;passwordXXX
    r1;jane;bigfish
    ";
                server1.Start(server1Settings);
                server1.LoadAccountsFromString(accountInfo);
                deelie1 = new RadiusServerDeelie(server1, RadiusServerDeelie.Mode.IgnoreAlternatePackets);

                server2.Start(server2Settings);
                server2.LoadAccountsFromString(accountInfo);
                deelie2 = new RadiusServerDeelie(server2, RadiusServerDeelie.Mode.IgnoreAlternatePackets);

                client.Open(clientSettings);

                for (int i = 0; i < 10; i++)
                {
                    Assert.IsTrue(client.Authenticate("r1", "jeff", "password123"));
                }
            }
            finally
            {
                server1.Stop();
                server2.Stop();
                client.Close();
            }
        }
示例#22
0
        public void RadiusClient_LoadBalance_MultiPort()
        {
            // Verify that the client actually distributes packets across multiple
            // RADIUS servers with a multi port client.

            RadiusServer         server1         = new RadiusServer();
            RadiusServer         server2         = new RadiusServer();
            RadiusServerSettings server1Settings = new RadiusServerSettings();
            RadiusServerSettings server2Settings = new RadiusServerSettings();
            RadiusClient         client          = new RadiusClient();
            RadiusClientSettings clientSettings  = new RadiusClientSettings(new NetworkBinding[] { Local_RADIUS, Local_AAA }, "hello");
            RadiusServerDeelie   deelie1;
            RadiusServerDeelie   deelie2;

            server1Settings.RealmFormat = RealmFormat.Email;
            server1Settings.Devices.Add(new RadiusNasInfo(IPAddress.Loopback, "hello"));
            server1Settings.Devices.Add(new RadiusNasInfo(NetHelper.GetActiveAdapter(), "hello"));
            server1Settings.NetworkBinding = new IPEndPoint(IPAddress.Any, NetworkPort.RADIUS);

            server2Settings.RealmFormat = RealmFormat.Email;
            server2Settings.Devices.Add(new RadiusNasInfo(IPAddress.Loopback, "hello"));
            server2Settings.Devices.Add(new RadiusNasInfo(NetHelper.GetActiveAdapter(), "hello"));
            server2Settings.NetworkBinding = new IPEndPoint(IPAddress.Any, NetworkPort.AAA);

            clientSettings.RealmFormat      = RealmFormat.Email;
            clientSettings.PortCount        = 4;
            clientSettings.MaxTransmissions = 1;

            try
            {
                string accountInfo = @"

    // This is a comment line

    r1;jeff;password123
    r2;jeff;passwordXXX
    r1;jane;bigfish
    ";
                server1.Start(server1Settings);
                server1.LoadAccountsFromString(accountInfo);
                deelie1 = new RadiusServerDeelie(server1, RadiusServerDeelie.Mode.Normal);

                server2.Start(server2Settings);
                server2.LoadAccountsFromString(accountInfo);
                deelie2 = new RadiusServerDeelie(server2, RadiusServerDeelie.Mode.Normal);

                client.Open(clientSettings);

                for (int i = 0; i < 20; i++)
                {
                    Assert.IsTrue(client.Authenticate("r1", "jeff", "password123"));
                }

                Assert.IsTrue(deelie1.Packets.Count > 0);
                Assert.IsTrue(deelie2.Packets.Count > 0);
            }
            finally
            {
                server1.Stop();
                server2.Stop();
                client.Close();
            }
        }
        /// <summary>
        /// Called by AD FS to perform the actual authentication.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="proofData"></param>
        /// <param name="request"></param>
        /// <param name="claims"></param>
        /// <returns> If the Authentication Adapter has successfully performed
        /// the authentication a claim of type
        /// http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod
        /// is returned
        /// </returns>
        public IAdapterPresentation TryEndAuthentication(IAuthenticationContext context, IProofData proofData, System.Net.HttpListenerRequest request, out System.Security.Claims.Claim[] claims)
        {
            claims = null;
            IAdapterPresentation result = null;

            // Ensure the submitted form isn't empty.
            if (proofData == null || proofData.Properties == null || !proofData.Properties.ContainsKey("pin"))
            {
                if (this.debugLogging)
                {
                    Logging.LogMessage("Either proofData is null or does not contain required property");
                }
                throw new ExternalAuthenticationException(resMgr.GetString("Error_InvalidPIN", new System.Globalization.CultureInfo(context.Lcid)), context);
            }
            string pin      = proofData.Properties["pin"].ToString();
            string userName = this.identityClaim.Split('\\')[1];

            // Construct RADIUS auth request.
            var authPacket = radiusClient.Authenticate(userName, pin);

            byte[] bIP = IPAddress.Parse(appConfig.NasAddress).GetAddressBytes();
            authPacket.SetAttribute(new RadiusAttribute(RadiusAttributeType.NAS_IP_ADDRESS, bIP));
            var receivedPacket = radiusClient.SendAndReceivePacket(authPacket).Result;

            // Handle no response from RADIUS server.
            if (receivedPacket == null)
            {
                if (this.debugLogging)
                {
                    Logging.LogMessage("No response received from RADIUS server.");
                }
                throw new ExternalAuthenticationException(resMgr.GetString("Error_RADIUS_NULL", new System.Globalization.CultureInfo(context.Lcid)), context);
            }

            // Examine the different RADIUS responses
            switch (receivedPacket.PacketType)
            {
            case RadiusCode.ACCESS_ACCEPT:
                System.Security.Claims.Claim claim = new System.Security.Claims.Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/otp");
                claims = new System.Security.Claims.Claim[] { claim };
                break;

            case RadiusCode.ACCESS_CHALLENGE:
                // No way to cater for this. Fail.
                result = new AdapterPresentation(resMgr.GetString("Error_RADIUS_ACCESS_CHALLENGE", new System.Globalization.CultureInfo(context.Lcid)), false);
                break;

            case RadiusCode.ACCESS_REJECT:
                result = new AdapterPresentation(resMgr.GetString("Error_InvalidPIN", new System.Globalization.CultureInfo(context.Lcid)), false);
                break;

            default:
                result = new AdapterPresentation(resMgr.GetString("Error_RADIUS_OTHER", new System.Globalization.CultureInfo(context.Lcid)), false);
                break;
            }

            if (this.debugLogging)
            {
                Logging.LogMessage(
                    "Processed authentication response." + Environment.NewLine +
                    "Packet Type: " + receivedPacket.PacketType.ToString() + Environment.NewLine +
                    "User: " + this.identityClaim);
            }

            return(result);
        }
示例#24
0
        /// <summary>
        /// Entry point
        /// </summary>
        /// <returns></returns>
        public static int Main()
        {
            _defaultLogFolder = Settings.Default.LogFolder;

            if (string.IsNullOrEmpty(_defaultLogFolder))
            {
                return(5);
            }

            InitLogger();

            var username = Environment.GetEnvironmentVariable("username");
            var password = Environment.GetEnvironmentVariable("password");

            if (string.IsNullOrEmpty(username))
            {
                Log.ErrorLog.WriteLine("environment variable 'username' is undefined undefined");
                return(1);
            }

            if (string.IsNullOrEmpty(password))
            {
                Log.ErrorLog.WriteLine("environment variable 'password' is undefined undefined");
                return(1);
            }

            if (Config.Settings == null)
            {
                Log.ErrorLog.WriteLine("Config is empty/unreadable");
                return(2);
            }

            if (Config.Settings.Servers == null || Config.Settings.Servers.Count == 0)
            {
                Log.ErrorLog.WriteLine("No servers found in config");
                return(3);
            }

            var res = Parallel.ForEach(Config.Settings.Servers.Cast <ServerElement>(), (server, state) =>
            {
                Log.InformationLog.WriteLine(string.Format("server name = {0} , retries = {1}, wait = {2}, autport = {3}",
                                                           server.Name, server.retries, server.wait, server.authport));

                var rc = new RadiusClient(server.Name, server.sharedsecret, server.wait * 1000, server.authport);

                Log.InformationLog.WriteLine("Radius client initializated");

                try
                {
                    var authPacket = rc.Authenticate(username, password);
                    if (Config.Settings.NAS_IDENTIFIER != null)
                    {
                        authPacket.SetAttribute(new RadiusAttribute(RadiusAttributeType.NAS_IDENTIFIER, Encoding.ASCII.GetBytes(Config.Settings.NAS_IDENTIFIER)));
                    }

                    authPacket.SetAttribute(new RadiusAttribute(RadiusAttributeType.NAS_PORT_TYPE, BitConverter.GetBytes((int)NasPortType.ASYNC)));

                    var receivedPacket = rc.SendAndReceivePacket(authPacket, server.retries).Result;

                    if (receivedPacket != null && receivedPacket.PacketType == RadiusCode.ACCESS_ACCEPT)
                    {
                        state.Stop();
                    }
                }
                catch (Exception ex)
                {
                    Log.ErrorLog.WriteLine(ex);
                }
            });

            if (res.IsCompleted)
            {
                //On a parcouru tous les srveurs et on n'a rien trouvé
                Log.ErrorLog.WriteLine(string.Format("Authentication failed for: {0}", username));
                return(4);
            }
            else
            {
                Log.SuccessLog.WriteLine(string.Format("Authentication success for user {0}", username));
                return(0);
            }
        }