RouterOs MySql Freeradius

From MikroTik Wiki
Revision as of 10:27, 13 August 2007 by Janisk (talk | contribs) (Reverted edits by BysA59 (Talk); changed back to last version by Martin)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Mikrotik and Freeradius 1.0.4+ with MySql For PPP Authentication

This guide assumes you have a working Linux system (for the purpose of this guide Ubuntu 5.10 is used), The Linux system can communicate with the RouterOs system and you have a basic understanding of Linux and MySql commands. The purpose of this document is to walk you through the steps needed to configure freeradius, get freeradius talking to MySql and finally getting your RouterOs system to authenticate and assign IP's for PPP* connections.

  • All of the commands in the following guide assumes you are logged into *NIX systems as root or RouterOs systems as Admin

Setting Up Freeradius

Once you have installed freeradius with the MySql module on your Linux system its time to tidy up the base configuration. This guide assumes that the freeradius server will ONLY be serving RouterOs systems. In order for Mikrotik & freeradius to work nicely together a lot of unnecessary options/features in freeradius must be removed or turned off, we start this by trimming radiusd.conf

radiusd.conf

  • An example of a trimmed radiusd.conf can be found Here - This is in production use on a Ubuntu 5.10 server processing requests for PPPoE, We will now run through the file and i will explain what options do what
prefix = /usr
exec_prefix = /usr
sysconfdir = /etc
localstatedir = /var
sbindir = ${exec_prefix}/sbin
logdir = /var/log/freeradius
raddbdir = /etc/freeradius
radacctdir = ${logdir}/radacct

confdir = ${raddbdir}
run_dir = ${localstatedir}/run/freeradius

log_file = ${logdir}/radius.log

libdir = /usr/lib/freeradius
pidfile = ${run_dir}/freeradius.pid

user = freerad
group = freerad

The above options are specific to your installation of freeradius and may be different from these, do not overwrite your local setting with the above settings, you may find your freeradius server not long functions correctly - it is generally better to leave these settings alone

max_request_time = 30
delete_blocked_requests = no
cleanup_delay = 5
max_requests = 1024
bind_address = *

These settings control your server, what you should change here is the max_requests setting and the bind address, max_requests should be set to 256 * Number of routers using this radius server, it is better to set this number too high than it is to set it too low, if this number is too low the server will stop responding to radius requests when under load. For this example I have said that 4 RouterOs devices will use this radius server so 1024 is an ideal number. Alter the ‘bind_address’ if you have multiple network interfaces or ip’s on the *NIX box, otherwise it's safe to leave it how it is

port = 0

hostname_lookups = no
allow_core_dumps = no

Leave these off, its better for everyone

regular_expressions     = yes
extended_expressions    = yes

Depending on how your freeradius server was compiled you can use RegEx, if it was turned on when freeradius was compiled then you are able to turn it either on or off, if it was not turned on at compile time then you are unable to turn it on, doing so will cause freeradius to error at startup

log_stripped_names = yes
log_auth = no
log_auth_badpass = no
log_auth_goodpass = no

The above section is really just to stop your log files clogging up, for debugging you could turn the above options to 'Yes' but there are better ways to debug failed radius requests which I will show you later in the guide

usercollide = no

Turning this on may rip a hole in the fabric of space-time, actually the doc's just say may result in the server behaving strangely. However in versions 1.1+ this can be used to check for stale connections in the radius database, this is something not needed is a simple setup but it may be usefull if the server is going to be under heavy production load

lower_user = before
lower_pass = before

This will change all the usernames and passwords on incoming radius requests to lower case, i prefer this in my network as we only allow lower case usernames when users sign up, however if you add users to freeradius with mixed case or upper case this will cause freeradius to reject the request

nospace_user = before
nospace_pass = before

This is the same again, only this time it will remove and spaced in the username and password

checkrad = ${sbindir}/checkrad

We leave this alone - it just does checks on the NAS devices

security {
       max_attributes = 200
       reject_delay = 1
       status_server = no
}

This sets the maximum number of radius attributes in a incoming or outgoing radius packet, I prefer to leave it at its default of 200 however those that will use this radius server ONLY for mikrotik you can safely set this to 10-30. Reject delay slows down brute force cracking attempts, however it slows down debugging and testing so during testing we set this to 1. In a production server this should be set around 3-5 Status server is turned off because its useless, its only included for legacy support to from devices that use radius - Mikrotik is not one of these devices

proxy_requests  = no

We won’t be running a radius proxy so we can turn this off

$INCLUDE  ${confdir}/clients.conf

After we have cleaned this file up we will setup clients.conf, this is NOT where you setup users but where you setup the devices that are allowed to use the radius server

snmp    = no

I don’t use SNMP on my network to monitor the freeradius server

thread pool {
       start_servers = 5
       max_servers = 32
       min_spare_servers = 3
       max_spare_servers = 10
       max_requests_per_server = 0
}

This controls how many 'process' are spawned by freeradius, you can tweak these settings for fine turning the server's performance, max_requests_per_server should be altered to 512 or 1024, this is the number of requests that the child process will handle before dying, it helps avoid issues where a child process is locked up

modules {
       pap {
               encryption_scheme = crypt
       }
       chap {
               authtype = CHAP
       }
       mschap {
               authtype = MS-CHAP
               use_mppe = no
       }

This defines the authentication methods used by freeradius, in this case we will use pap,chap and mschap

       acct_unique {
               key = "User-Name, Acct-Session-Id, NAS-IP-Address, Client-IP-Address, NAS-Port"
       }

This creates a unique account ID for accounting updates, sometimes devices can reuse the same accounting ID which causes problems. Mikrotik doesn’t do this as far as I am aware but its better safe than sorry

       $INCLUDE  ${confdir}/sql.conf

This includes the MySql configuration for the server, we will be altering this file soon

       counter daily {
               filename = ${raddbdir}/db.daily
               key = User-Name
               count-attribute = Acct-Session-Time
               reset = daily
               counter-name = Daily-Session-Time
               check-name = Max-Daily-Session
               allowed-servicetype = Framed-User
               cache-size = 5000
       }

Since our users may be connected for more than 24 hours at a time we keep this in here, it will reset some attributes daily so that the accounting packets work correctly

       always fail {
               rcode = fail
       }
       always reject {
               rcode = reject
       }
       always ok {
               rcode = ok
               simulcount = 0
               mpp = no
       }
}

These are here for debugging purposes, so we leave them alone

instantiate {
}
authorize {
       chap
       mschap
       sql
}
authenticate {
       Auth-Type PAP {
               pap
       }
       Auth-Type CHAP {
               chap
       }
       Auth-Type MS-CHAP {
               mschap
       }
}
preacct {
       acct_unique 
}
accounting {
       sql
}
session {
       sql
}
post-auth {
       sql
}

These are all setup to point to the MySql database for their purpose


clients.conf

Next up we have to alter sql.conf and clients.conf, we will start with clients.conf which is used to setup which devices are allowed to use freeradius and a password for basic security.

Once again the trimmed clients.conf file can be found Here

client 127.0.0.1 {
       secret          = somepassword
       shortname       = localhost
       nastype     = other
}

Always keep this in the file - it allows the server itself to use the freeradius server, it’s helpful for testing and debugging. 'secret' is the password that the device using freeradius must have before it can start using freeradius 'shortname' is a simple identifier for use in logging, if you have a lot of devices using a single freeradius server it can make debugging a lot easier by having a different shortname for each device 'nastype' is always set to other when the device is RouterOs

client 192.168.0.2 {
       secret          = somepassword
       shortname       = SingleRouter
       nastype     = mikrotik
}

In this example we have specified a single IP address on a network

client 192.168.0.0/24 {
       secret          = somepassword
       shortname       = Subnet
       nastype     = mikrotik
}

Here we have defined an entire IP subnet rather than a single IP, this should be AVOIDED at all costs, it allows devices on the network to access the radius server that you may not want having access

Clients.conf is rather simple to setup, where possible only allow single IP's as it will decrease the risk of someone on your network hacking the server



sql.conf

This file defines the connection to your MySql server, MySql can be running locally on the same server or can be hosted off site

  • Be aware that if the MySql server is hosted off site and goes down all freeradius requests will be rejected until freeradius can connect to the MySql server again

Trimmed file is Here

sql {

       driver = "rlm_sql_mysql"
       server = "192.168.0.5"
       login = "radius"
       password = "hackme"
       radius_db = "radius"

This is the server IP address,username/password and database needed for freeradius to connect to the MySql database, you should change this before trying to run freeradius

       acct_table1 = "radacct"
       acct_table2 = "radacct"

       postauth_table = "radpostauth"
       authcheck_table = "radcheck"
       authreply_table = "radreply"
       groupcheck_table = "radgroupcheck"
       groupreply_table = "radgroupreply"
       usergroup_table = "usergroup"

The above defines the structure of the database and where freeradius should look for it's information

       deletestalesessions = yes

Its best to leave this on

       sqltrace = no
       sqltracefile = ${logdir}/sqltrace.sql

If you are having trouble with MySql you can turn this on and it will log all MySql commands freeradius executes

       num_sql_socks = 5
       connect_failure_retry_delay = 60

The number of connection's freeradius will keep open to the MySql server and how long it will wait before trying to reconnect if the MySql server goes down

Removed to keep page formatting nice The rest of the file had to be removed to make sure page formatting remained tidy, it contained the exact SQL query freeradius uses for various database look ups, unless you know what you are doing do not alter this section

}

dictionary

The last file we have to edit is the dictionary, (/etc/freeradius/dictionary), this is the file that defines all the attributes that freeradius uses to talk to RouterOS, the Mikrotik-dictionary is included in the freeradius package, we simply need to include it in the main dictionary file.

$INCLUDE	/usr/share/freeradius/dictionary

#	Include the Mikrotik specific dictionary
$INCLUDE        /usr/share/freeradius/dictionary.mikrotik

Congrats! Freeradius is now setup on the server, but don’t start freeradius just yet - you will find it wont work as we need to setup the MySql database with the correct tables.


SettingUp Mysql

This is a simple task of importing an SQL file into the database, then setting up the MySql user and finally granting the correct permissions.

The hardest part I found was finding a copy of the sql schema to import, Once again freeradius.sql is Here. This guide assumes you are not completely new to MySql, RouterOs or Radius and as such i will not walk you thought importing the file or setting up the MySql user. If you are unable to do this then you need to have a look at if you are the right person to be putting radius into place for your company


Once you have imported the sql file and setup the MySql user with the right permissions then you should be able to start up the freeradius server like this

freeradius -x

All going well you should see this

Starting - reading configuration files ...
Module: Loaded PAP
Module: Instantiated pap (pap)
Module: Loaded CHAP
Module: Instantiated chap (chap)
Module: Loaded MS-CHAP
Module: Instantiated mschap (mschap)
Module: Loaded SQL
rlm_sql (sql): Driver rlm_sql_mysql (module rlm_sql_mysql) loaded and linked
rlm_sql (sql): Attempting to connect to radius@124.157.64.2:/radius
rlm_sql (sql): starting 0
rlm_sql (sql): Attempting to connect rlm_sql_mysql #0
rlm_sql_mysql: Starting connect to MySQL server for #0
rlm_sql (sql): Connected new DB handle, #0
rlm_sql (sql): starting 1
rlm_sql (sql): Attempting to connect rlm_sql_mysql #1
rlm_sql_mysql: Starting connect to MySQL server for #1
rlm_sql (sql): Connected new DB handle, #1
rlm_sql (sql): starting 2
rlm_sql (sql): Attempting to connect rlm_sql_mysql #2
rlm_sql_mysql: Starting connect to MySQL server for #2
rlm_sql (sql): Connected new DB handle, #2
rlm_sql (sql): starting 3
rlm_sql (sql): Attempting to connect rlm_sql_mysql #3
rlm_sql_mysql: Starting connect to MySQL server for #3
rlm_sql (sql): Connected new DB handle, #3
rlm_sql (sql): starting 4
rlm_sql (sql): Attempting to connect rlm_sql_mysql #4
rlm_sql_mysql: Starting connect to MySQL server for #4
rlm_sql (sql): Connected new DB handle, #4
Module: Instantiated sql (sql)
Module: Loaded Acct-Unique-Session-Id
Module: Instantiated acct_unique (acct_unique)
Initializing the thread pool...
Listening on authentication *:1812
Listening on accounting *:1813
Ready to process requests.

If you do then pat yourself on the back, the hardest part is done now. If not then freeradius is very good at its error messages, For example

rlm_sql_mysql: Mysql error 'Access denied for user 'root'@'mao.ubernet.co.nz' (using password: YES)'

Tells you that either you MySql permissions are not setup correctly or you didn’t setup sql.conf correctly


Crash Course On Radius

At this point its a good time to explain what goes on in a basic radius transaction and how it interacts with the MySql database

  • Client Desktop Attempts PPPoE connection

RouterOS Router recives PPPoE connection attempt, looks at local PPP users first then sends a "Access-Request" packet to freeradius

Sending Access-Request of id 0 to 192.168.0.2:1812
 User-Name = "testing"
 User-Password = "testing"
  • Freeradius connect to MySql database and looks at "radcheck" table for user-name 'testing', If freeradius finds a row with the right username it will check the password against the user-password sent in the access-request packet otherwise freeradius with send an "Access-Reject" packet back and RouterOs will decline the Client Desktop's Attempt for PPPoE
  • If freeradius finds a correct match of user-name and user-password then it looks in "radreply" for any and all rows that contain the user-name, if none are found then an "Access-Accept"
Access-Accept packet from host 192.168.0.2:1812, id=0, length=20
  • If freeradius does find rows however it will send those rows back with the "Access-Accept" like this:
Access-Accept packet from host 192.168.0.2:1812, id=0, length=43
Framed-IP-Address = 127.0.0.1
Rate-Limit = "256k/256k"

To sum it all up

  1. Client Talks to RouterOs
  2. RouterOS looks at itself then looks to Freeradius
  3. Freeradius connects to MySql
  4. Freeradius checks some things in MySql and send back the response
  5. RouterOs acts on this reponses

Radius is a VERY powerful protocol and it's very complex - using it with RouterOs for PPP* is easy once you understand how freeradius check it's information and where it looks for reply attributes

Setting Up Users In MySql

Now that you know about how freeradius does things its time to start adding users into the database, for this example i will walk you though the raw SQL commands to create and new user with a password and IP address of '192.168.0.100' How you enter the sql into MySql comes down to personal taste, some will use the 'mysql' command in *NIX others will use a front-end like phpmyadmin - It doesn’t matter as long as the commands are entered correctly.

The first thing freeradius looks for is the user-name, then it makes sure that supplied password matches the password in MySql. We setup the sql like this

INSERT INTO radcheck ( id , UserName , Attribute , op , Value ) 
VALUES ( NULL , 'test-user', 'user-password', '==', 'test-pass');

In your case replace test-user and test-pass with your username and password. Now that freeradius will accept our user-name and user-password we should tell it some attributes to reply with, like our static IP address

INSERT INTO radreply ( id , UserName , Attribute , op , Value )
VALUES (NULL , 'test-user', 'Framed-IP-Address', '=', '192.168.0.100');

Simple as that the user is created and given a static IP address, repeat the last sql statement with as many attributes as you want

Testing What We Have Done So Far

So you've gotten this far, by now you should have:

  1. A running freeradius server that’s lean and mean
  2. MySql server with the freeradius database and user setup
  3. A user loaded with a static IP address

If you don't then try to Google any errors or the Mikrotik Forums If you do then GREAT!

So let’s test,

Radius Client

Radtest, This comes with freeradius package in Debian/Ubuntu and others, to test our setup as it is with radtest we do the following

radtest test-user test-pass 192.168.0.2 10 somepassword

And you should see the following

root@test-mikrotik:/#radtest test-user test-pass 192.168.0.2 10 somepass
Sending Access-Request of id 223 to 192.168.0.2:1812
       User-Name = "test-user"
       User-Password = "test-pass"
       NAS-IP-Address = 192.168.0.5
       NAS-Port = 10
rad_recv: Access-Accept packet from host 192.168.0.2:1812, id=223, length=26
       Framed-IP-Address = 192.168.0.100
root@test-mikrotik:/#

If the above test fails the following are some common errors

root@test-mikrotik:/#radtest test-user test-pass 192.168.0.2 10 somepas
Sending Access-Request of id 7 to 124.157.64.6:1812
       User-Name = "test-user"
       User-Password = "test-pass"
       NAS-IP-Address = 192.168.0.5
       NAS-Port = 10
Re-sending Access-Request of id 7 to 124.157.64.6:1812
       User-Name = "test-user"
       User-Password = "\030&\375\273\031*@\340\340\023\263\270\347/!\360"
       NAS-IP-Address = 192.168.0.5
       NAS-Port = 10
rad_recv: Access-Reject packet from host 124.157.64.6:1812, id=7, length=20
rad_decode: Received Access-Reject packet from 124.157.64.6:1812 with invalid signature (err=2)!  (Shared secret is incorrect.)
radclient: radclient.c:440: send_one_packet: Assertion `radclient->reply == ((void *)0)' failed.
/usr/bin/radtest: line 53: 29190 Done                    ( echo "User-Name = \"$1\""; echo "User-Password = \"$2\""; echo   "NAS-IP-Address = $nas"; echo "NAS-Port = $4"; if [ "$6" ]; then
    echo "Framed-Protocol = PPP";
fi )
     29191 Aborted                 | $radclient $DICTIONARY -x $3 auth $5
root@test-mikrotik:/#

As you can see it's telling you the secret in clients.conf and the one you supplied do not match, check the secret and try again

root@test-mikrotik:/#radtest test-user test-pass 192.168.0.2 10 somepas
Sending Access-Request of id 32 to 124.157.64.6:1812
       User-Name = "test-user"
       User-Password = "test-pas"
       NAS-IP-Address = 192.168.0.5
       NAS-Port = 10
Re-sending Access-Request of id 32 to 124.157.64.6:1812
       User-Name = "test-user"
       User-Password = "\271[\023\241I\352I6\336zGJ\270\247\217\356"
       NAS-IP-Address = 192.168.0.5
       NAS-Port = 10
rad_recv: Access-Reject packet from host 124.157.64.6:1812, id=32, length=20
root@test-mikrotik:/ #

This one looks like your username or password supplied doesn’t match the one in the database, check it and try again

Any other errors you get mean you put the error message through Googleand if it still fails check your configuration from the top


Configuring RouterOs for Radius & PPP* AAA

  • This is designed for RouterOs 2.9, 2.8 Users may find none of the following works at all. On top of this it is designed for a clean router with no existing PPPoE servers or Radius client’s setup

Well now the end is insight, all that’s left now is to configure RouterOs as a radius client and tell the PPPoE server to use AAA.

RouterOs Radius Client

/radius add service=ppp address=192.168.0.2 secret=somepassword accounting-port=1813 authentication-port=1812 timeout=500ms

What this does is tell RouterOs that when a PPP user tries to login it will look to the local ppp users list and then will send a access-request packet to 192.168.0.2 with a secrey of 'somepassword' and will wait 500ms for a reply before resending

RouterOs PPP AAA setup

/ppp aaa set accounting=yes interim-update=5m use-radius=yes

This part tells RouterOs to use radius and to use accounting also, which will be updated every 5 minutes

Whats Left To Do

Well that’s the end of this guide, all that’s left to do now is setup a PPPoE server on the router and attempt to connect a user to do. If you get stuck remember to check the user-name and user-password is correct and you can put freeradius into verbose debug mode by going

freeeradius -x

Other wise Google is your friend then the Mikrotik Forums.

MySQL replication

MySQL replication is an easy way of creating hardware redundancy. MySQL replication can be done this way.

Note Use mysql-server-4.1 instead of the standard mysql-server(on Debian 3.1).

Slave configuration

Add to /etc/mysql/my.cnf:

[mysqld]
replicate-do-table      = radius.radcheck
replicate-do-table      = radius.radreply
replicate-do-table      = radius.radgroupcheck
replicate-do-table      = radius.radgroupreply
replicate-do-table      = radius.usergroup
replicate-do-table      = radius.userinfo

Start synchronisation

# mysql –prootpassword
mysql> change master to
    -> MASTER_HOST='master_host_name',
    -> MASTER_USER='replication_user_name',
    -> MASTER_PASSWORD='replication_password';
mysql> load data from master;

Last Words

I hope you find this guide helpful, I personally had a lot of trouble finding good information on how to setup freeradius best for use with RouterOs and alot of the configuration comes from a production server.

Stay tuned for more guides from me(Tristram) about using freeradius more in a Mikrotik Network(DHCP, Wifi Auth etc) In the mean time please leave some feedback on the talk page, Talk:RouterOs_MySql_Freeradius

Links to related articles

MRTG RADIUS MySQL Accounting - Monitor your user’s traffic with MRTG. Generates MRTG configuration and gets accounting information from MySQL.

RADIUS webfrontend - For easier administration, you can use this web interface.