Note: You are currently viewing documentation for Moodle 2.5. Up-to-date documentation for the latest stable version of Moodle may be available here: NTLM authentication.

NTLM authentication: Difference between revisions

From MoodleDocs
(Document the "Remote username format" configuration setting.)
 
(16 intermediate revisions by 9 users not shown)
Line 1: Line 1:
{{Moodle 1.9}}This document describes how to set up '''NTLM/Windows Integrated Authentication''' in Moodle.
{{Authentication}}This document describes how to set up '''NTLM/Windows Integrated Authentication''' in Moodle.  
 
This is integrated into Moodle 1.9 onwards.
 
For earlier versions, it uses a modified version of LDAP Authentication.
The NTLM Authentication module is available in the Modules and Plugins database here:
http://moodle.org/mod/data/view.php?d=13&rid=314
 
Note: When a particular note is specific to earlier versions of the NTLM plugin, this is noted by: '''(pre-1.9 only)'''.


==Overview==
==Overview==
Line 17: Line 9:
#The Server hosting your website is a member of the Active Directory Domain that your users are also members of.
#The Server hosting your website is a member of the Active Directory Domain that your users are also members of.
#You are able to define people inside your Network (and authenticated to the Domain) from an IP range of computers.
#You are able to define people inside your Network (and authenticated to the Domain) from an IP range of computers.
#'''(pre-1.9 only)''' You have "some" basic knowledge of php and are able to configure the index.php with the range of internal IP addresses.
#You are familar with or have read the LDAP authentication documentation.
#You are familar with or have read the LDAP authentication documentation.
#The Active Directory domain credentials of your users are returned as '''DOMAINNAME\username''' from your authentication service. If you are using the Winbind service from the Samba project, this can be untrue, depending on your Winbind configuration settings.
#The Active Directory domain credentials of your users are returned as '''DOMAINNAME\username''' from your authentication service. If you are using the Winbind service from the Samba project, this can be untrue, depending on your Winbind configuration settings. If you are using Moodle 2.4 or later, you can specify the format of the domain credentials (see below). If you are using an older version and you can not modify your settings to satisfy this last assumption, then you will need to remove or comment out the line that reads:
 
If you can not modify your settings to satisfy this last assumption, then you will need to remove or comment out the line that reads:
     $username = substr(strrchr($username, '\\'), 1); //strip domain info
     $username = substr(strrchr($username, '\\'), 1); //strip domain info
and add the relevant lines of code to extract the username part from the domain user credentials and store it in $username.
and add the relevant lines of code to extract the username part from the domain user credentials and store it in $username.




::'''VERY IMPORTANT''': In Moodle 1.9 and onwards, NTLM authentication depends on [[LDAP authentication]], and NTLM configuration is specified in the LDAP authentication settings page (Administration >> Users >> Authentication >> LDAP Server). So before trying to configure NTLM, make sure you have LDAP_authentication properly setup and working.
::'''VERY IMPORTANT''': NTLM authentication depends on [[LDAP authentication]], and NTLM configuration is specified in the LDAP authentication settings page (Site Administration >> Plugins >> Authentication >> LDAP Server). So before trying to configure NTLM, make sure you have LDAP_authentication properly setup and working.


==Installation on 1.9==
==Installation==


No installation needed. See the Administration >> Users >> Authentication >> LDAP Server for the NTLM config options. You only have to
No installation needed. See Site Administration >> Plugins >> Authentication >> LDAP Server for the NTLM config options. You only have to


*Enable NTLM SSO
*Enable NTLM SSO
*Set the IP/Subnet mask for the clients (see below)
*Set the IP/Subnet mask for the clients (see below)
*(Optionally) Set the "Remote username format" for your domain user credentials format (see below)
*On IIS: turn on Windows Authentication
*On IIS: turn on Windows Authentication
*On Apache - use one of the 3 methods outlined below
*On Apache - use one of the 3 methods outlined below
Line 47: Line 37:
Thus it is needed to set the IP subnet.
Thus it is needed to set the IP subnet.


If you have used previous versions of NTLM in your Moodle database you will need to make two further changes.  
If you have used previous versions of NTLM (from 1.8 and below) in your Moodle database you will need to make two further changes.  


#The type of authentication held against each user now needs to be LDAP, as NTLM will not be recognised. To edit the fields open up a SQL query for your Moodle server and use the following query "update mdl_user set auth = 'ldap' where auth = 'ntlm' "
#The type of authentication held against each user now needs to be LDAP, as NTLM will not be recognised. To edit the fields open up a SQL query for your Moodle server and use the following query "update mdl_user set auth = 'ldap' where auth = 'ntlm' "
#If you had a previous .htaccess file in the auth/ntlm directory, you will need to move it to the auth/ldap directory. Regardless of whether it is in a .htaccess file of the httpd.conf, the <Files> line now needs to refer to ntlmsso_magic.php. If it is in the httpd.conf, the <Directory> will need to change too. This is covered later on for new installs, but is one of the fundamental changes that needs to be made for those upgrading.
#If you had a previous .htaccess file in the auth/ntlm directory, you will need to move it to the auth/ldap directory. Regardless of whether it is in a .htaccess file of the httpd.conf, the <Files> line now needs to refer to ntlmsso_magic.php. If it is in the httpd.conf, the <Directory> will need to change too. This is covered later on for new installs, but is one of the fundamental changes that needs to be made for those upgrading.


==Installation on 1.6/1.7==
==How to Turn Integrated Authentication on==
#Copy the folder AUTH/NTLM into the AUTH folder of your moodle installation.
The auth/ldap/ntlmsso_magic.php file MUST have NTLM/Integrated Authentication enabled on the server or the authentication will not work.
#Configure IP/Subnet Mask in the Config screen  [[#Configuring_IP.2FSubnet_Mask|see below for more help]]. If the IP/Subnet Mask does not give enough complexity for your network, Modify the auth/ntlm/index.php file - for instructions on doing this, view the comments in the file.
#Turn Integrated Authentication ON and Anonymous Authentication OFF for the moodle\auth\ntlm\oncampuslogin.php file. [[#How_to_Turn_Integrated_Authentication_on|See below for more detailed instructions]]
#Visit the admin page of your moodle installation - you should see notification that the NTLM_AUTH module has been installed.
#go to the configuration > variables page, find the dbsessions setting (in 1.8 on admin page server \ sessions page), and set it to "YES" then save the page.
#go to the Authentication admin page and select auth_ntlmtitle as your authentication method Note: - this doesn't display full text as I haven't created a language file for this module - you will also see auth_ntlmdescription instead of a proper description - you don't need to worry about this, as you will be the only one who ever sees this.
#Configure this page with your normal LDAP settings. NOTE: the Alternate Login URL at the bottom of this page (or on the main authentication page in 1.8 - and needs to be set manually to the oncampus url)has been set to the NTLM page. - if you wish uninstall this auth module, you must reset this variable on the new authentication type page. eg - if you wish to revert back to manual authentication, then change to manual, and then make sure you delete the alternate login url at the bottom of the page.
#(OPTIONAL) modify the offcampuslogin page to give errors when students try to prefix their usercode with your domain.
around line 216 find this code, uncomment all the lines and replace the letters 'DOM' with your domain:


    if (empty($errormsg)) {
===IIS Configuration===
        if (strstr(strtolower($frm->username), "DOM\\") <> false) { //NAD - DOM messages.
Open the IIS Management Console and navigate to the auth/ldap/ntlmsso_magic.php file.
            $errormsg = get_string("invalidlogin") . " DOM\\ is not required!";
        } else if (strpos($frm->username, "@") <> false) {
            $errormsg = get_string("invalidlogin") . " enter your username - not your e-mail address.";
        } else {
            $errormsg = get_string("invalidlogin");
        }
    }
 
==Installation on 1.5==
 
See the README in the auth/ntml package.


==How to Turn Integrated Authentication on==
====IIS 6.0====
The File ntlmsso_magic.php (1.9 or above) or oncampuslogin.php (1.8 or below) MUST have NTLM/Integrated Authentication enabled at the server or the page will not work.
===IIS Configuration===
Open up IIS, and find the auth/ldap/ntlmsso_magic.php (1.9 or above) or auth/ntlm/oncampuslogin.php (1.8 or below) file,
#right click on the file, choose properties
#right click on the file, choose properties
#under the "file security" tab, click on the Authentication and Access control "edit" button
#under the "file security" tab, click on the Authentication and Access control "edit" button
#untick "Enable Anonymous Access" and tick "Integrated Windows Authentication"
#untick "Enable Anonymous Access" and tick "Integrated Windows Authentication"
#According to [http://moodle.org/mod/forum/discuss.php?d=145171#p634027 this post], if you are using IIS 7.5 (it comes with Windows Server 2008 R2), you have to select 'Windows Authentication' and click on 'Providers'. This shows a list of enabled providers (Negotiate and NTLM, by default). Change the order so that NTLM is at the top of the list.
 
====IIS 7.x====
#After navigating to the 'auth/ldap' folder, switch to Content View
#right click on the file, choose "Switch to Features View"
#click on the Authentication icon on the right
#select 'Anonymous Authentication' and click the 'Disable' button
#select 'Windows Authentication' and click the 'Enable' button
 
*According to [http://moodle.org/mod/forum/discuss.php?d=145171#p634027 this post], if you are using IIS 7.5 (it comes with Windows Server 2008 R2), you have to select 'Windows Authentication' and click on 'Providers'. This shows a list of enabled providers (Negotiate and NTLM, by default). Change the order so that NTLM is at the top of the list.
*If 'Windows Authentication' is not available, then you need to install it as a separate authentication provider (in Control Panel).


===APACHE Configuration===
===APACHE Configuration===
Line 98: Line 75:
   </IfModule>
   </IfModule>


* Install the Samba <tt>winbind</tt> daemon package. This packages relies on Samba's configuration file to get some important settings (like the Windows domain name, uid and gid range mappings, and so on). In addition to that, you'll need to make your Linux/Unix machine part of the domain. Otherwise winbind won't be able to pull user and groups informationi from the domain controllers. You should read the Samba documentation to perform this step, but the most important part is having something like the following lines in your <code>smb.conf</code> file (in addition to what you already have there):
* Install the Samba <tt>winbind</tt> daemon package. This packages relies on Samba's configuration file to get some important settings (like the Windows domain name, uid and gid range mappings, and so on). In addition to that, you'll need to make your Linux/Unix machine part of the domain. Otherwise winbind won't be able to pull user and groups informationi from the domain controllers. You should read the Samba documentation to perform this step, but the most important part is having something like the following lines in your <code>smb.conf</code> file, inside the [global] section (in addition to what you already have there):


   workgroup = DOMAINNAME
   workgroup = DOMAINNAME
Line 176: Line 153:
::-- Hi Dan! I made it work using Ubuntu 7.04. That's what I've used to update the documentation. [[User:Iñaki Arenaza|Iñaki Arenaza]] 10:43, 30 September 2007 (CDT)
::-- Hi Dan! I made it work using Ubuntu 7.04. That's what I've used to update the documentation. [[User:Iñaki Arenaza|Iñaki Arenaza]] 10:43, 30 September 2007 (CDT)
::-- Hi Dan! I have this working on Ubuntu 8.04 LTS in an RM CC4 Active Directory Domain. [[User:munk3h|Ian]] 16:31 15 December 2009 (GMT)
::-- Hi Dan! I have this working on Ubuntu 8.04 LTS in an RM CC4 Active Directory Domain. [[User:munk3h|Ian]] 16:31 15 December 2009 (GMT)
::-- Hi Dan, Running on Ubuntu 10.04 Lucid, Apache2 got this running in no time flat with AD v6. Worth noting that if Using Iñaki Arenaza's LDAP Clone plugin, you will need to add another copy of the Directory tag in <tt>apache2.conf</tt> pointing at the new ldap plugin. --[[User:Christopher O&#39;Kelly|Christopher O&#39;Kelly]] 10:09, 16 April 2012 (WST)
::-- Hi Dan. On Ubuntu 12.04 there is no need to compile anything to do this. *sudo apt-get install php5-ldap
*sudo apt-get install libapache2-mod-auth-ntlm-winbind *sudo a2enmod auth_ntlm_winbind *sudo apt-get install winbind smbfs smbclient samba


====Using the NTLM Auth Module for Apache on Linux====
====Using the NTLM Auth Module for Apache on Linux====
Line 196: Line 176:
::* mod_auth_sspi-1.0.4-2.0.58.zip :  Use this file if you are using Apache 2.0.x.
::* mod_auth_sspi-1.0.4-2.0.58.zip :  Use this file if you are using Apache 2.0.x.
::* mod_auth_sspi-1.0.4-2.2.2.zip :  Use this file if you are using Apache 2.2.x.
::* mod_auth_sspi-1.0.4-2.2.2.zip :  Use this file if you are using Apache 2.2.x.
If you are using an x64 version of Apache mod_auth_sspi x64 versions are available from https://www.apachehaus.net/modules/mod_auth_sspi/
These files '''do not''' work with Apache versions 2.4.x.


* Unzip the right file and copy mod_auth_sspi.so (it's inside '''bin''' subdirectory) to your Apache modules directory.
* Unzip the right file and copy mod_auth_sspi.so (it's inside '''bin''' subdirectory) to your Apache modules directory.
Line 216: Line 200:
             SSPIOfferBasic Off
             SSPIOfferBasic Off
             SSPIAuthoritative On
             SSPIAuthoritative On
             SSPIDomain mycollege.ac.uk
             SSPIDomain <YOUR AD DOMAIN>
             require valid-user
             require valid-user
         </Files>
         </Files>
Line 228: Line 212:
             SSPIOfferBasic Off
             SSPIOfferBasic Off
             SSPIAuthoritative On
             SSPIAuthoritative On
             SSPIDomain mycollege.ac.uk
             SSPIDomain <YOUR AD DOMAIN>
             require valid-user
             require valid-user
         </Files>
         </Files>
Line 239: Line 223:
     </Directory>
     </Directory>


:: '''For 1.9 or above''':
:::Create a new text file named '.htaccess' in the directory 'C:\moodle\moodle\auth\ldap' and add the following directives:
:::Create a new text file named '.htaccess' in the directory 'C:\moodle\moodle\auth\ldap' and add the following directives:
     <Files ntlmsso_magic.php>
     <Files ntlmsso_magic.php>
Line 251: Line 234:
     </Files>
     </Files>


:: '''For 1.8 or below''':
:This enables the Moodle folder to be moved to any apache webserver that is configured to allow authentication configuration through .htaccess
:::Create a new text file named '.htaccess' in the directory 'C:\moodle\moodle\auth\ntlm' and add the following directives:
 
    <Files oncampuslogin.php>
Lastly for Internet Explorer 7 onwards you must also replace this line in your httpd-ssl.conf file:  
        AuthName "Moodle at My College"
 
        AuthType SSPI
  BrowserMatch ".*MSIE.*" \
        SSPIAuth On
 
        SSPIOfferBasic Off
with
        SSPIAuthoritative On
        SSPIDomain mycollege.ac.uk
        require valid-user
    </Files>


:This enables the Moodle folder to be moved to any apache webserver that is configured to allow authentication configuration through .htaccess
  BrowserMatch ".*MSIE [2-5]\..*" \


For further help and discussion: http://moodle.org/mod/forum/discuss.php?d=56565
For further help and discussion: http://moodle.org/mod/forum/discuss.php?d=56565
Line 307: Line 286:
#Use the ktpass.exe utility to map the service principal and create a keytab file
#Use the ktpass.exe utility to map the service principal and create a keytab file
Apache requires a keytab file, which is generated with ktpass.exe on the Windows Active Directory Domain Controller.
Apache requires a keytab file, which is generated with ktpass.exe on the Windows Active Directory Domain Controller.
Shockingly, this component of Windows Server 2003 SP1 does not function correctly so one must obtain a hot fix: http://support.microsoft.com/kb/919557
Unfortunately, this component of Windows Server 2003 SP1 does not function correctly so one must obtain a hot fix: http://support.microsoft.com/kb/919557


Run the following command on the domain controller:
Run the following command on the domain controller:
Line 334: Line 313:
</pre>
</pre>


*Replace the '''ntlmsso_magic''' function in '''/auth/ldap/auth.php''' (1.9 and later only?) with the following code:
*Replace the '''ntlmsso_magic''' function in '''/auth/ldap/auth.php''' (1.9 only, as 2.x already support Kerberos format out of the box, just specify that format in the "Authentication type" setting) with the following code:


<pre>
<pre>
     function ntlmsso_magic($sesskey) {
     function ntlmsso_magic($sesskey) {
         if (isset($_SERVER['REMOTE_USER']) && !empty($_SERVER['REMOTE_USER'])) {
         if (isset($_SERVER['REMOTE_USER']) && !empty($_SERVER['REMOTE_USER'])) {
            $username = $_SERVER['REMOTE_USER'];


/**
            // HTTP __headers__ seem to be sent in ISO-8859-1 encoding
  * begin kerberos - afhole@wortech.ac.uk 21-04-2009
            // (according to my reading of RFC-1945, RFC-2616 and RFC-2617 and
  */
            // my local tests), so we need to convert the REMOTE_USER value
if ( $pos = strpos($username, "@") )
            // (i.e., what we got from the HTTP WWW-Authenticate header) into UTF-8
{
            $textlib = textlib_get_instance();
$username = substr($username, 0, $pos);
            $username = $textlib->convert($_SERVER['REMOTE_USER'], 'iso-8859-1', 'utf-8');
} else {
           
$username = substr(strrchr($username, '\\'), 1); //strip domain info
            /**
}
            * begin kerberos - afhole@wortech.ac.uk 21-04-2009
/**
            */
  * end kerberos
            if ($pos = strpos($username, "@")) {
  */
                $username = substr($username, 0, $pos);
            } else {
                $username = substr(strrchr($username, '\\'), 1); //strip domain info
            }
            /**
            * end kerberos
            */
 
             $username = moodle_strtolower($username); //compatibility hack
             $username = moodle_strtolower($username); //compatibility hack
             set_cache_flag('auth/ldap/ntlmsess', $sesskey, $username, AUTH_NTLMTIMEOUT);
             set_cache_flag('auth/ldap/ntlmsess', $sesskey, $username, AUTH_NTLMTIMEOUT);
Line 361: Line 343:
         }
         }
         return false;
         return false;
     }</code>
     }
 
</pre>
</pre>


Line 369: Line 350:
==Configuring IP/Subnet Mask==
==Configuring IP/Subnet Mask==
Subnet masks are based on binary patterns so need a bit of knowledge to understand. The best way to find out what IP/Subnet masks to use is to ask your Network Admin.  
Subnet masks are based on binary patterns so need a bit of knowledge to understand. The best way to find out what IP/Subnet masks to use is to ask your Network Admin.  
* '''(pre-1.9 only)''' Once you have configured your IP/Subnet masks, you can use the check_ip.php page to test if you have set these ranges up correctly.
 
* The new way of specifiying subnets is even easier/more flexible than before 1.9. Just type them one after the other, separated by commas. You can use several syntaxes:
* The new way of specifiying subnets is even easier/more flexible than before 1.9. Just type them one after the other, separated by commas. You can use several syntaxes:
** Type the network-number/prefix-length combination. E.g. 192.168.1.0/24
** Type the network-number/prefix-length combination. E.g. 192.168.1.0/24
Line 386: Line 367:
   10.1., 10.2., 172.16., 192.168.100.0/28
   10.1., 10.2., 172.16., 192.168.100.0/28
:(the last one cannot be expressed as a network 'prefix' as the netmask does not fall on an octect boundary).
:(the last one cannot be expressed as a network 'prefix' as the netmask does not fall on an octect boundary).
==Configuring Domain user credentials format==
If you are using Moodle 2.4 and later there is a new setting that lets you configure the format of the domain user credentials, instead of using the old fixed format. The setting is called "Remote username format". If you leave this seting empty, the default '''DOMAINNAME\username''' format will be used. You can use the optional '''%domain%''' placeholder to specify where the domain name appears, and the mandatory '''%username%''' placeholder to specify where the username appears.
Some widely used formats are:
* '''%domain%\%username%''' : MS Windows default, contains the domain name, followed by a backlash character, followed by the username.
* '''%username%@%domain%''' : This is the same format used by Kerberos (domain name followed by an at sign, followed by the username).
* '''%domain%/%username%''' : Some people configure Samba+Winbind to use this format.
* '''%domain%+%username%''' : Some people configure Samba+Winbind to use this other format.
* '''%username%''' : Only contains the username, with no domain part.


==Notes/Tips==
==Notes/Tips==
# '''(pre-1.9 only)''' When using IIS, dbsessions is required to be set to "YES" because when Integrated authentication is turned on for the oncampuslogin.php page, and dbsessions is set to "NO" then the server impersonates the user to write the session in the moodledata\sessions folder. The recommended fix is to set dbsessions to "YES" so that sessions are stored in the db. The non-recommended alternative method is to allow domain users write access to the sessions directory.
 
# '''(pre-1.9 only)''' If you forget to change the internal IP addresses in index.php to your own, you can just use the offcampuslogin url to login using your admin account. eg: http://yoursite.com/moodle/auth/ntlm/offcampuslogin.php
#If you are using Firefox, you will need to follow these steps:
#If you are using Firefox, you will need to follow these steps:
:*Load Firefox and type about:config in the address box. The configuration settings page should be displayed.
:*Load Firefox and type about:config in the address box. The configuration settings page should be displayed.
Line 399: Line 389:
# If the account in your AD management console shows like "First Last", you better change the ldap settings parameter 'User Attribute' from its default of {blank} / 'cn' to 'sAMAccountName' as indicated in [http://moodle.org/mod/forum/discuss.php?d=132364#p682173 this post]. The reason is that the cn name generally looks like "First Last", once you done the ldap sync, the user name in moodle will be "first last", but IE passes the account of "domain\first.last" to moodle which does not exist in moodle.
# If the account in your AD management console shows like "First Last", you better change the ldap settings parameter 'User Attribute' from its default of {blank} / 'cn' to 'sAMAccountName' as indicated in [http://moodle.org/mod/forum/discuss.php?d=132364#p682173 this post]. The reason is that the cn name generally looks like "First Last", once you done the ldap sync, the user name in moodle will be "first last", but IE passes the account of "domain\first.last" to moodle which does not exist in moodle.


==Specific File information (pre-1.9 only)==  
== To get a domain name for Moodle working on IIS7.5 Windows 2008 R2 ==
(mainly for developers)
Refer to http://support.microsoft.com/kb/896861. Key section listed below.
#auth\ntlm\index.php<br />This is the page used for the Alternate Login URL setting on the config page for the NTLM plugin.<br>The index.php file handles which login page to use based on the IP address of the user.<br>if inside your network, they should be directed to the oncampuslogin.php screen.<br>if outside your network, they should be directed to the offcampuslogin.php screen.<br>you will need to modify the if statements in this file to match the IP ranges inside your network.
Click Start, click Run, type regedit, and then click OK.<br />
#auth\ntlm\index_form.html<br />this is a copy of the file login\index_form.php.<br /> The only change in this file from the standard one is that the form action="index.php" is changed to form action="offcampuslogin.php" this is because anyone who is displayed the form will be an offcampus user.
In Registry Editor, locate and then click the following registry key:
#auth\ntlm\offcampuslogin.php<br />this is a copy of the file moodle\login\index.php with a couple of minor modifications.<br />the modifications to this file involve the setting of a variable ($onoroffcampus = "offcampus";) this is used by the auth plugin to define which page is being used for authentication. the other modification is for displaying extra error messages to the user. - with all the authentication methods we have students are constantly confused about how to enter their credentials if you use NTLM authentication elsewhere at your site you will be aware of the users having to enter the domain\username when authenticating. - this code block sits around line 215 in the file.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0<br />
#auth\ntlm\oncampuslogin.php<br />this is a copy of the file login\index.php<br />This file has been modified to get the details of the authenticated user via NTLM.
Right-click MSV1_0, point to New, and then click Multi-String Value.<br />
Type BackConnectionHostNames, and then press ENTER.<br />
Right-click BackConnectionHostNames, and then click Modify.<br />
In the Value data box, type the host name or the host names for the sites that are on the local computer, and then click OK.<br />
Quit Registry Editor, and then restart the IISAdmin service.


==Compiling mod_auth_ntlm_winbind on Debian/Ubuntu==
==Compiling mod_auth_ntlm_winbind on Debian/Ubuntu==
Line 429: Line 423:
*[http://moodle.org/mod/forum/view.php?id=42 Using Moodle: User authentication] forum
*[http://moodle.org/mod/forum/view.php?id=42 Using Moodle: User authentication] forum
*Using Moodle [http://moodle.org/mod/forum/discuss.php?d=45887 NTLM Authentication] forum discussion
*Using Moodle [http://moodle.org/mod/forum/discuss.php?d=45887 NTLM Authentication] forum discussion
*Using Moodle [http://moodle.org/mod/forum/discuss.php?d=80104 Merging AD NTLM SSO into auth/ldap] forum discussion
*Using Moodle [http://moodle.org/mod/forum/discuss.php?d=186661 Moodle in a DMZ with NTLM] forum discussion
*[http://moodle.org/mod/data/view.php?d=13&rid=314 Download the NTLM Authentication Module]
*[http://moodle.org/mod/data/view.php?d=13&rid=314 Download the NTLM Authentication Module]
*Using Moodle [http://moodle.org/mod/forum/discuss.php?d=80104 Merging AD NTLM SSO into auth/ldap] forum discussion


[[Category:Contributed code]]
[[Category:Contributed code]]
[[Category:Authentication]]


[[fr:Authentification NTLM]]
[[fr:Authentification NTLM]]

Latest revision as of 15:39, 16 October 2013

This document describes how to set up NTLM/Windows Integrated Authentication in Moodle.

Overview

Integrated Windows Authentication uses the security features of Windows clients and servers. It does not prompt users for a user name and password. The current Windows user information on the client computer is supplied by the browser through a challenge/response authentication process with the Web server for the Moodle site.

Assumptions

  1. You are running MS Active Directory for Authentication.
  2. The Server hosting your website is a member of the Active Directory Domain that your users are also members of.
  3. You are able to define people inside your Network (and authenticated to the Domain) from an IP range of computers.
  4. You are familar with or have read the LDAP authentication documentation.
  5. The Active Directory domain credentials of your users are returned as DOMAINNAME\username from your authentication service. If you are using the Winbind service from the Samba project, this can be untrue, depending on your Winbind configuration settings. If you are using Moodle 2.4 or later, you can specify the format of the domain credentials (see below). If you are using an older version and you can not modify your settings to satisfy this last assumption, then you will need to remove or comment out the line that reads:
   $username = substr(strrchr($username, '\\'), 1); //strip domain info

and add the relevant lines of code to extract the username part from the domain user credentials and store it in $username.


VERY IMPORTANT: NTLM authentication depends on LDAP authentication, and NTLM configuration is specified in the LDAP authentication settings page (Site Administration >> Plugins >> Authentication >> LDAP Server). So before trying to configure NTLM, make sure you have LDAP_authentication properly setup and working.

Installation

No installation needed. See Site Administration >> Plugins >> Authentication >> LDAP Server for the NTLM config options. You only have to

  • Enable NTLM SSO
  • Set the IP/Subnet mask for the clients (see below)
  • (Optionally) Set the "Remote username format" for your domain user credentials format (see below)
  • On IIS: turn on Windows Authentication
  • On Apache - use one of the 3 methods outlined below
  • On the client pc's, you might need to set the moodle server ip/moodle url as being in "local intranet" (From IE, tools -> options -> security -> local intranet)

It is important to note the following conditions must be satisfied to let NTLM SSO happens:

  • you've arrived to the login page with one GET request
  • you've ldap->ntlmsso_enabled
  • you've ldap->ntlmsso_subnet
  • you aren't logged
  • the IP of the client is in ntlmsso_subnet

Thus it is needed to set the IP subnet.

If you have used previous versions of NTLM (from 1.8 and below) in your Moodle database you will need to make two further changes.

  1. The type of authentication held against each user now needs to be LDAP, as NTLM will not be recognised. To edit the fields open up a SQL query for your Moodle server and use the following query "update mdl_user set auth = 'ldap' where auth = 'ntlm' "
  2. If you had a previous .htaccess file in the auth/ntlm directory, you will need to move it to the auth/ldap directory. Regardless of whether it is in a .htaccess file of the httpd.conf, the <Files> line now needs to refer to ntlmsso_magic.php. If it is in the httpd.conf, the <Directory> will need to change too. This is covered later on for new installs, but is one of the fundamental changes that needs to be made for those upgrading.

How to Turn Integrated Authentication on

The auth/ldap/ntlmsso_magic.php file MUST have NTLM/Integrated Authentication enabled on the server or the authentication will not work.

IIS Configuration

Open the IIS Management Console and navigate to the auth/ldap/ntlmsso_magic.php file.

IIS 6.0

  1. right click on the file, choose properties
  2. under the "file security" tab, click on the Authentication and Access control "edit" button
  3. untick "Enable Anonymous Access" and tick "Integrated Windows Authentication"

IIS 7.x

  1. After navigating to the 'auth/ldap' folder, switch to Content View
  2. right click on the file, choose "Switch to Features View"
  3. click on the Authentication icon on the right
  4. select 'Anonymous Authentication' and click the 'Disable' button
  5. select 'Windows Authentication' and click the 'Enable' button
  • According to this post, if you are using IIS 7.5 (it comes with Windows Server 2008 R2), you have to select 'Windows Authentication' and click on 'Providers'. This shows a list of enabled providers (Negotiate and NTLM, by default). Change the order so that NTLM is at the top of the list.
  • If 'Windows Authentication' is not available, then you need to install it as a separate authentication provider (in Control Panel).

APACHE Configuration

There are currently 3 possible methods for this:

Using the NTLM part of Samba for Apache on Linux

  • Get the plugin here: http://samba.org/ftp/unpacked/lorikeet/mod_auth_ntlm_winbind/ . You need to download all the files from the link, but not the contrib and debian directories. Then follow the instructions given inside the README file. If you are using Debian/Ubuntu, you can follow these compilation instructions.
  • Once you have compiled it, put it inside Apache's modules subdirectory (this location depends on a number of factors, like compiling Apache yourself, using different Linux distributions packages, an so on), and load and enable the module in Apache's configuration. For example, if your Apache modules are under /usr/lib/apache2/modules, you'll need something like this in your Apache configuration file (usually called apache2.conf or http2.conf):
  <IfModule !mod_auth_ntlm_winbind.c>
      LoadModule auth_ntlm_winbind_module /usr/lib/apache2/modules/mod_auth_ntlm_winbind.so
  </IfModule>
  • Install the Samba winbind daemon package. This packages relies on Samba's configuration file to get some important settings (like the Windows domain name, uid and gid range mappings, and so on). In addition to that, you'll need to make your Linux/Unix machine part of the domain. Otherwise winbind won't be able to pull user and groups informationi from the domain controllers. You should read the Samba documentation to perform this step, but the most important part is having something like the following lines in your smb.conf file, inside the [global] section (in addition to what you already have there):
 workgroup = DOMAINNAME
 password server = *
 security = domain
 encrypt passwords = true
 idmap uid = 10000-20000
 idmap gid = 10000-20000
and executing the command (as root):
 # net join DOMAINNAME -U Administrator
where DOMAINNAME is the NetBIOS windows domain name, and Administrator an account with enough privileges to add new machines to the domain.
You'll need to type this account's password for the command to succeed.
In Windows environments you could also try executing the command (as root):
 # net join DOMAINNAME -S DCSERVER -U Administrator
where DCSERVER is the Domain Controller server
Also, make sure you have disabled "Microsoft Network Server: digitally sign communications (always)" in your Domain Controllers Security Policy, unless you are using a version of Samba that can sign SMB packets.
  • Restart the winbind service to apply the changes and test that it's running ok by executing:
 $ wbinfo -u
You should get the full list of Windows domain users. If you use -g instead, you'll get the domain groups list.
  • Check that your winbind package installed the authentication helper command ntlm_auth, as we'll need it later. We'll assume the helper is located at /usr/bin/ntlm_auth. If yours is at a different location, make sure you adjust the path in the example below.
  • Add something like this to your Apache configuration file (usually called apache2.conf or http2.conf). We'll assume that your Moodle $CFG->dirroot directory is located at /var/www/moodle in the example:
For 1.9 or above use:
   <Directory "/var/www/moodle/auth/ldap/">
       <Files ntlmsso_magic.php>
           NTLMAuth on
           AuthType NTLM
           AuthName "Moodle NTLM Authentication"
           NTLMAuthHelper "/usr/bin/ntlm_auth --helper-protocol=squid-2.5-ntlmssp"
           NTLMBasicAuthoritative on
           require valid-user
       </Files>
   </Directory>
For 1.8 or below use:
   <Directory "/var/www/moodle/auth/ntlm/">
       <Files oncampuslogin.php>
           NTLMAuth on
           AuthType NTLM
           AuthName "Moodle NTLM Authentication"
           NTLMAuthHelper "/usr/bin/ntlm_auth --helper-protocol=squid-2.5-ntlmssp"
           NTLMBasicAuthoritative on
           require valid-user
       </Files>
   </Directory>
  • Check the permissions of the Winbind pipe directory (Ubuntu places it under /var/run/samba/winbindd_privileged, yours may be placed at a different location). Apache will need to be able to enter that directory, so we need to make sure it has the right permissions. So have a look at the permissions of that directory and note the name of the group assigned to it. The following example is from a Ubuntu 7.10 machine:
 $ ls -ald /var/run/samba/winbindd_privileged
 drwxr-x--- 2 root winbindd_priv 60 2007-11-17 16:18 /var/run/samba/winbindd_privileged/
so we see the group is winbindd_priv.
  • Instead of modifying the directory permissions (which could break other services that use winbind) we are going to make the Apache user (www-data in our example, but could be httpd, or nobody, etc.) is part of the appropiate group. Execute the following as root:
 # adduser www-data winbindd_priv
adduser is available in Debian and Ubuntu at least. If your distribution doesn't have adduser, you can edit /etc/group manually to achive the same effect.
  • Stop and start the Apache service to apply the changes. Have a look at Apache's error log to see that everything is ok.

simply change the line to that was:

KeepAlive Off

to:

KeepAlive On

and restart apache (/etc/init.d/http restart)

  • Email Dan if you get this working - I'm keen to hear how people go using the samba winbind option!
-- Hi Dan! I made it work using Ubuntu 7.04. That's what I've used to update the documentation. Iñaki Arenaza 10:43, 30 September 2007 (CDT)
-- Hi Dan! I have this working on Ubuntu 8.04 LTS in an RM CC4 Active Directory Domain. Ian Ohr 16:31 15 December 2009 (GMT)
-- Hi Dan, Running on Ubuntu 10.04 Lucid, Apache2 got this running in no time flat with AD v6. Worth noting that if Using Iñaki Arenaza's LDAP Clone plugin, you will need to add another copy of the Directory tag in apache2.conf pointing at the new ldap plugin. --Christopher O'Kelly 10:09, 16 April 2012 (WST)
-- Hi Dan. On Ubuntu 12.04 there is no need to compile anything to do this. *sudo apt-get install php5-ldap
  • sudo apt-get install libapache2-mod-auth-ntlm-winbind *sudo a2enmod auth_ntlm_winbind *sudo apt-get install winbind smbfs smbclient samba

Using the NTLM Auth Module for Apache on Linux

The NTLM Auth module is a bit stale and even its authors suggest that you use the NTLM part of Samba with Apache on Linux

Get it from here

  1. get the Module from: http://modntlm.sourceforge.net/
  2. follow the instructions given there and inside the README that comes with the package.

I (Iñaki Arenaza) strongly recommend using the NTLM part of Samba with Apache on Linux over this module. It's better maintained, more robust and has more features.

Using the mod_auth_sspi Module for Apache 2 on Windows

NOTE: This setup is currently being used in a live production environment, and is therefore suitable for such use provided it is correctly configured and tested.

This is the recommended method for Apache 2 on Windows, however it will not work on Linux/UNIX systems. It provides better stability and higher performance than other NTLM modules.

  • mod_auth_sspi-1.0.4-2.0.58.zip : Use this file if you are using Apache 2.0.x.
  • mod_auth_sspi-1.0.4-2.2.2.zip : Use this file if you are using Apache 2.2.x.

If you are using an x64 version of Apache mod_auth_sspi x64 versions are available from https://www.apachehaus.net/modules/mod_auth_sspi/

These files do not work with Apache versions 2.4.x.

  • Unzip the right file and copy mod_auth_sspi.so (it's inside bin subdirectory) to your Apache modules directory.
  • Edit your Apache 2 configuration file (httpd.conf) to load the module.
   <IfModule !mod_auth_sspi.c>
       LoadModule sspi_auth_module modules/mod_auth_sspi.so
   </IfModule>
  • Choose one of the two methods below
Method 1: This method is recommended for servers that will host a single Moodle instance. Configure NTLM from the main configuration file, add the following to httpd.conf (substitute "C:\moodle" with the path to your Moodle installation e.g. "C:\my-moodle"
For 1.9 or above use:
   <Directory "C:\moodle\auth\ldap">
       <Files ntlmsso_magic.php>
           AuthName "Moodle at My College"
           AuthType SSPI
           SSPIAuth On
           SSPIOfferBasic Off
           SSPIAuthoritative On
           SSPIDomain <YOUR AD DOMAIN>
           require valid-user
       </Files>
   </Directory>
For 1.8 or below use:
   <Directory "C:\moodle\auth\ntlm">
       <Files oncampuslogin.php>
           AuthName "Moodle at My College"
           AuthType SSPI
           SSPIAuth On
           SSPIOfferBasic Off
           SSPIAuthoritative On
           SSPIDomain <YOUR AD DOMAIN>
           require valid-user
       </Files>
   </Directory>
Method 2: The alternative method is to use a .htaccess file
This method is recommended for servers that will host multiple Moodle instances. It allows additional Moodle instances to be configured without restarting apache, and also makes the solution a little more portable. We need to add a directive to the main httpd.conf to allow configuration of authentication within .htaccess files.
   <Directory C:\moodle>
       AllowOverride AuthConfig
   </Directory>
Create a new text file named '.htaccess' in the directory 'C:\moodle\moodle\auth\ldap' and add the following directives:
   <Files ntlmsso_magic.php>
       AuthName "Moodle at My College"
       AuthType SSPI
       SSPIAuth On
       SSPIOfferBasic Off
       SSPIAuthoritative On
       SSPIDomain mycollege.ac.uk
       require valid-user
   </Files>
This enables the Moodle folder to be moved to any apache webserver that is configured to allow authentication configuration through .htaccess

Lastly for Internet Explorer 7 onwards you must also replace this line in your httpd-ssl.conf file:

 BrowserMatch ".*MSIE.*" \ 

with

 BrowserMatch ".*MSIE [2-5]\..*" \ 

For further help and discussion: http://moodle.org/mod/forum/discuss.php?d=56565

Using the Kerberos Auth Module for Apache on Linux/UNIX (mod_auth_kerb)

Environment details in this example:

  1. Active Directory Domain: EXAMPLE.AC.UK
  2. Active Directory Domain Controller: dc.example.ac.uk
  3. Linux/UNIX web server: moodle.example.ac.uk
  4. Active Directory user account for web server service principal: moodlekerb

Install kerberos on moodle.example.ac.uk and enter the following in krb5.conf (by default: /etc/krb5.conf)

[libdefaults]
    default_realm = EXAMPLE.AC.UK
[domain_realm]
    example.ac.uk = EXAMPLE.AC.UK
[realms]
     EXAMPLE.AC.UK = {
                      admin_server = dc.example.ac.uk
                      kdc          = dc.example.ac.uk
                    }:
* Test kerberos
Issue the following command at the shell prompt:
<pre>
$> kinit user@EXAMPLE.AC.UK

Where 'user' is an Active Directory account for which you know the password.

Next, issue the following:

$>klist

If all is OK it will list the Kerberos ticket you were granted from the domain controller (KDC)

  • Create HTTP service principal for moodle.example.ac.uk
  1. Create the 'moodlekerb' user account in Active Directory (NOT a machine account) to map to the web server service principal (HTTP/moodle.example.ac.uk@EXAMPLE.AC.UK)

NOTE: moodle.example.ac.uk MUST be the canonical DNS name of the server i.e. an A record (NOT a CNAME). Additionally a valid PTR (reverse DNS) record must exist and match the corresponding A record.

  1. Use the ktpass.exe utility to map the service principal and create a keytab file

Apache requires a keytab file, which is generated with ktpass.exe on the Windows Active Directory Domain Controller. Unfortunately, this component of Windows Server 2003 SP1 does not function correctly so one must obtain a hot fix: http://support.microsoft.com/kb/919557

Run the following command on the domain controller:

C:\path\to\hotfix\ktpass.exe -princ HTTP/moodle.example.ac.uk@EXAMPLE.AC.UK -mapuser EXAMPLE\moodlekerb -crypto DES-CBC-MD5 +DesOnly +setPass +rndPass -ptype KRB5_NT_PRINCIPAL -out moodle.example.ac.uk.keytab

Copy C:\path\to\hotfix\moodle.example.ac.uk.keytab to the moodle web server and remember the location (/etc/httpd/moodle.example.ac.uk.keytab or similar)

  • Configure Apache / mod_auth_kerb

Edit the Apache configuration for the moodle host and add the following directives:

        <Directory /path/to/moodle/docs/auth/ldap/>
                <Files ntlmsso_magic.php>
                        AuthName "Moodle"
                        AuthType Kerberos
                        KrbAuthRealms EXAMPLE.AC.UK
                        KrbServiceName HTTP
                        Krb5Keytab /etc/httpd/moodle.example.ac.uk.keytab
                        KrbMethodNegotiate on
                        KrbMethodK5Passwd on
                        KrbAuthoritative on
                        require valid-user
                </Files>
        </Directory>
  • Replace the ntlmsso_magic function in /auth/ldap/auth.php (1.9 only, as 2.x already support Kerberos format out of the box, just specify that format in the "Authentication type" setting) with the following code:
    function ntlmsso_magic($sesskey) {
        if (isset($_SERVER['REMOTE_USER']) && !empty($_SERVER['REMOTE_USER'])) {

            // HTTP __headers__ seem to be sent in ISO-8859-1 encoding
            // (according to my reading of RFC-1945, RFC-2616 and RFC-2617 and
            // my local tests), so we need to convert the REMOTE_USER value
            // (i.e., what we got from the HTTP WWW-Authenticate header) into UTF-8
            $textlib = textlib_get_instance();
            $username = $textlib->convert($_SERVER['REMOTE_USER'], 'iso-8859-1', 'utf-8');
            
            /**
             * begin kerberos - afhole@wortech.ac.uk 21-04-2009
             */
            if ($pos = strpos($username, "@")) {
                $username = substr($username, 0, $pos);
            } else {
                $username = substr(strrchr($username, '\\'), 1); //strip domain info
            }
            /**
             * end kerberos
             */

            $username = moodle_strtolower($username); //compatibility hack
            set_cache_flag('auth/ldap/ntlmsess', $sesskey, $username, AUTH_NTLMTIMEOUT);
            return true;
        }
        return false;
    }

The above code change will account for the fact that Kerberos presents the username to REMOTE_USER in the format user@DOMAIN, rather than NTLM's DOMAIN\user

Configuring IP/Subnet Mask

Subnet masks are based on binary patterns so need a bit of knowledge to understand. The best way to find out what IP/Subnet masks to use is to ask your Network Admin.

  • The new way of specifiying subnets is even easier/more flexible than before 1.9. Just type them one after the other, separated by commas. You can use several syntaxes:
    • Type the network-number/prefix-length combination. E.g. 192.168.1.0/24
    • Type the network 'prefix', ending in a period character. E.g. 192.168.1.
    • Type the network address range (this only works for the last address octect). E.g. 192.168.1.1-254
All the three examples refer to the same subnetwork. So assuming you need to specify the following subnetworks:
  • 10.1.0/255.255.0.0
  • 10.2.0.0/255.255.0.0
  • 172.16.0.0/255.255.0.0
  • 192.168.100.0/255.255.255.240
You can type:
10.1.0.0/16, 10.2.0.0/16, 172.16.0.0/16, 192.168.100.0/28
or:
 10.1.0.0/16, 10.2.0.0/16, 172.16.0.0/16, 192.168.100.240-255
or even:
 10.1., 10.2., 172.16., 192.168.100.0/28
(the last one cannot be expressed as a network 'prefix' as the netmask does not fall on an octect boundary).

Configuring Domain user credentials format

If you are using Moodle 2.4 and later there is a new setting that lets you configure the format of the domain user credentials, instead of using the old fixed format. The setting is called "Remote username format". If you leave this seting empty, the default DOMAINNAME\username format will be used. You can use the optional %domain% placeholder to specify where the domain name appears, and the mandatory %username% placeholder to specify where the username appears.

Some widely used formats are:

  • %domain%\%username% : MS Windows default, contains the domain name, followed by a backlash character, followed by the username.
  • %username%@%domain% : This is the same format used by Kerberos (domain name followed by an at sign, followed by the username).
  • %domain%/%username% : Some people configure Samba+Winbind to use this format.
  • %domain%+%username% : Some people configure Samba+Winbind to use this other format.
  • %username% : Only contains the username, with no domain part.

Notes/Tips

  1. If you are using Firefox, you will need to follow these steps:
  • Load Firefox and type about:config in the address box. The configuration settings page should be displayed.
  • In the Filter box, type the word "ntlm" to filter the NTLM strings. You should see three settings displayed.
  • Double-click on "network.automatic-ntlm-auth.trusted-uris".
  • In the box, enter the full URL of your Moodle server. For example
    http://moodle.mydomain.com, (the comma is important)
  • Close Firefox and restart.
  1. NTLM seems to not work at all when BASIC authentication is enabled. (this was using the Kerberos method, other ways may work)
  2. If the account in your AD management console shows like "First Last", you better change the ldap settings parameter 'User Attribute' from its default of {blank} / 'cn' to 'sAMAccountName' as indicated in this post. The reason is that the cn name generally looks like "First Last", once you done the ldap sync, the user name in moodle will be "first last", but IE passes the account of "domain\first.last" to moodle which does not exist in moodle.

To get a domain name for Moodle working on IIS7.5 Windows 2008 R2

Refer to http://support.microsoft.com/kb/896861. Key section listed below. Click Start, click Run, type regedit, and then click OK.
In Registry Editor, locate and then click the following registry key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0
Right-click MSV1_0, point to New, and then click Multi-String Value.
Type BackConnectionHostNames, and then press ENTER.
Right-click BackConnectionHostNames, and then click Modify.
In the Value data box, type the host name or the host names for the sites that are on the local computer, and then click OK.
Quit Registry Editor, and then restart the IISAdmin service.

Compiling mod_auth_ntlm_winbind on Debian/Ubuntu

You need to install the following packages (and all of their dependencies) by using aptitude, synaptic, etc.:

 autoconf apache2-threaded-dev debian-builder

Once you have them installed, open up a text console, go to the directory where you downloaded the mod_auth_ntlm_winbind files an execute the following commands (as a normal user):

 autoconf
 ./configure --with-apxs=/usr/bin/apxs2 --with-apache=/usr/sbin/apache2
 make

That should compile it without errors. Then as a user that can run commands as root via sudo, execute the following command from the same directory:

 sudo make install

This will create the final mod_auth_ntlm_winbind.so file and install it under /usr/lib/apache2/modules, with the rest of the Apache 2 modules (the size of the file and last modification time shown below may differ from your install):

 ls -l /usr/lib/apache2/modules/mod_auth_ntlm_winbind.so
 -rw-r--r-- 1 root root 20921 2009-02-17 04:27 /usr/lib/apache2/modules/mod_auth_ntlm_winbind.so

See also