PageRenderTime 22ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/auth/shibboleth/auth.php

https://bitbucket.org/kudutest1/moodlegit
PHP | 446 lines | 222 code | 71 blank | 153 comment | 59 complexity | 10fa74cc5f365430d405781597b9edad MD5 | raw file
  1. <?php
  2. /**
  3. * @author Martin Dougiamas
  4. * @author Lukas Haemmerle
  5. * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
  6. * @package moodle multiauth
  7. *
  8. * Authentication Plugin: Shibboleth Authentication
  9. *
  10. * Authentication using Shibboleth.
  11. *
  12. * Distributed under GPL (c)Markus Hagman 2004-2006
  13. *
  14. * 10.2004 SHIBBOLETH Authentication functions v.0.1
  15. * 05.2005 Various extensions and fixes by Lukas Haemmerle
  16. * 10.2005 Added better error messags
  17. * 05.2006 Added better handling of mutli-valued attributes
  18. * 2006-08-28 File created, code imported from lib.php
  19. * 2006-10-27 Upstream 1.7 changes merged in, added above credits from lib.php :-)
  20. * 2007-03-09 Fixed authentication but may need some other changes
  21. * 2007-10-03 Removed requirement for email address, surname and given name on request of Markus Hagman
  22. * 2008-01-21 Added WAYF functionality
  23. */
  24. if (!defined('MOODLE_INTERNAL')) {
  25. die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
  26. }
  27. require_once($CFG->libdir.'/authlib.php');
  28. /**
  29. * Shibboleth authentication plugin.
  30. */
  31. class auth_plugin_shibboleth extends auth_plugin_base {
  32. /**
  33. * Constructor.
  34. */
  35. function auth_plugin_shibboleth() {
  36. $this->authtype = 'shibboleth';
  37. $this->config = get_config('auth/shibboleth');
  38. }
  39. /**
  40. * Returns true if the username and password work and false if they are
  41. * wrong or don't exist.
  42. *
  43. * @param string $username The username (with system magic quotes)
  44. * @param string $password The password (with system magic quotes)
  45. * @return bool Authentication success or failure.
  46. */
  47. function user_login($username, $password) {
  48. global $SESSION;
  49. // If we are in the shibboleth directory then we trust the server var
  50. if (!empty($_SERVER[$this->config->user_attribute])) {
  51. // Associate Shibboleth session with user for SLO preparation
  52. $sessionkey = '';
  53. if (isset($_SERVER['Shib-Session-ID'])){
  54. // This is only available for Shibboleth 2.x SPs
  55. $sessionkey = $_SERVER['Shib-Session-ID'];
  56. } else {
  57. // Try to find out using the user's cookie
  58. foreach ($_COOKIE as $name => $value){
  59. if (preg_match('/_shibsession_/i', $name)){
  60. $sessionkey = $value;
  61. }
  62. }
  63. }
  64. // Set shibboleth session ID for logout
  65. $SESSION->shibboleth_session_id = $sessionkey;
  66. return (strtolower($_SERVER[$this->config->user_attribute]) == strtolower($username));
  67. } else {
  68. // If we are not, the user has used the manual login and the login name is
  69. // unknown, so we return false.
  70. return false;
  71. }
  72. }
  73. /**
  74. * Returns the user information for 'external' users. In this case the
  75. * attributes provided by Shibboleth
  76. *
  77. * @return array $result Associative array of user data
  78. */
  79. function get_userinfo($username) {
  80. // reads user information from shibboleth attributes and return it in array()
  81. global $CFG;
  82. // Check whether we have got all the essential attributes
  83. if ( empty($_SERVER[$this->config->user_attribute]) ) {
  84. print_error( 'shib_not_all_attributes_error', 'auth_shibboleth' , '', "'".$this->config->user_attribute."' ('".$_SERVER[$this->config->user_attribute]."'), '".$this->config->field_map_firstname."' ('".$_SERVER[$this->config->field_map_firstname]."'), '".$this->config->field_map_lastname."' ('".$_SERVER[$this->config->field_map_lastname]."') and '".$this->config->field_map_email."' ('".$_SERVER[$this->config->field_map_email]."')");
  85. }
  86. $attrmap = $this->get_attributes();
  87. $result = array();
  88. $search_attribs = array();
  89. foreach ($attrmap as $key=>$value) {
  90. // Check if attribute is present
  91. if (!isset($_SERVER[$value])){
  92. $result[$key] = '';
  93. continue;
  94. }
  95. // Make usename lowercase
  96. if ($key == 'username'){
  97. $result[$key] = strtolower($this->get_first_string($_SERVER[$value]));
  98. } else {
  99. $result[$key] = $this->get_first_string($_SERVER[$value]);
  100. }
  101. }
  102. // Provide an API to modify the information to fit the Moodle internal
  103. // data representation
  104. if (
  105. $this->config->convert_data
  106. && $this->config->convert_data != ''
  107. && is_readable($this->config->convert_data)
  108. ) {
  109. // Include a custom file outside the Moodle dir to
  110. // modify the variable $moodleattributes
  111. include($this->config->convert_data);
  112. }
  113. return $result;
  114. }
  115. /**
  116. * Returns array containg attribute mappings between Moodle and Shibboleth.
  117. *
  118. * @return array
  119. */
  120. function get_attributes() {
  121. $configarray = (array) $this->config;
  122. $moodleattributes = array();
  123. foreach ($this->userfields as $field) {
  124. if (isset($configarray["field_map_$field"])) {
  125. $moodleattributes[$field] = $configarray["field_map_$field"];
  126. }
  127. }
  128. $moodleattributes['username'] = $configarray["user_attribute"];
  129. return $moodleattributes;
  130. }
  131. function prevent_local_passwords() {
  132. return true;
  133. }
  134. /**
  135. * Returns true if this authentication plugin is 'internal'.
  136. *
  137. * @return bool
  138. */
  139. function is_internal() {
  140. return false;
  141. }
  142. /**
  143. * Returns true if this authentication plugin can change the user's
  144. * password.
  145. *
  146. * @return bool
  147. */
  148. function can_change_password() {
  149. return false;
  150. }
  151. /**
  152. * Hook for login page
  153. *
  154. */
  155. function loginpage_hook() {
  156. global $SESSION, $CFG;
  157. // Prevent username from being shown on login page after logout
  158. $CFG->nolastloggedin = true;
  159. return;
  160. }
  161. /**
  162. * Hook for logout page
  163. *
  164. */
  165. function logoutpage_hook() {
  166. global $SESSION, $redirect;
  167. // Only do this if logout handler is defined, and if the user is actually logged in via Shibboleth
  168. $logouthandlervalid = isset($this->config->logout_handler) && !empty($this->config->logout_handler);
  169. if (isset($SESSION->shibboleth_session_id) && $logouthandlervalid ) {
  170. // Check if there is an alternative logout return url defined
  171. if (isset($this->config->logout_return_url) && !empty($this->config->logout_return_url)) {
  172. // Set temp_redirect to alternative return url
  173. $temp_redirect = $this->config->logout_return_url;
  174. } else {
  175. // Backup old redirect url
  176. $temp_redirect = $redirect;
  177. }
  178. // Overwrite redirect in order to send user to Shibboleth logout page and let him return back
  179. $redirect = $this->config->logout_handler.'?return='.urlencode($temp_redirect);
  180. }
  181. }
  182. /**
  183. * Prints a form for configuring this authentication plugin.
  184. *
  185. * This function is called from admin/auth.php, and outputs a full page with
  186. * a form for configuring this plugin.
  187. *
  188. * @param array $page An object containing all the data for this page.
  189. */
  190. function config_form($config, $err, $user_fields) {
  191. include "config.html";
  192. }
  193. /**
  194. * Processes and stores configuration data for this authentication plugin.
  195. *
  196. *
  197. * @param object $config Configuration object
  198. */
  199. function process_config($config) {
  200. global $CFG;
  201. // set to defaults if undefined
  202. if (!isset($config->auth_instructions) or empty($config->user_attribute)) {
  203. $config->auth_instructions = get_string('auth_shib_instructions', 'auth_shibboleth', $CFG->wwwroot.'/auth/shibboleth/index.php');
  204. }
  205. if (!isset ($config->user_attribute)) {
  206. $config->user_attribute = '';
  207. }
  208. if (!isset ($config->convert_data)) {
  209. $config->convert_data = '';
  210. }
  211. if (!isset($config->changepasswordurl)) {
  212. $config->changepasswordurl = '';
  213. }
  214. if (!isset($config->login_name)) {
  215. $config->login_name = 'Shibboleth Login';
  216. }
  217. // Clean idp list
  218. if (isset($config->organization_selection) && !empty($config->organization_selection) && isset($config->alt_login) && $config->alt_login == 'on') {
  219. $idp_list = get_idp_list($config->organization_selection);
  220. if (count($idp_list) < 1){
  221. return false;
  222. }
  223. $config->organization_selection = '';
  224. foreach ($idp_list as $idp => $value){
  225. $config->organization_selection .= $idp.', '.$value[0].', '.$value[1]."\n";
  226. }
  227. }
  228. // save settings
  229. set_config('user_attribute', $config->user_attribute, 'auth/shibboleth');
  230. if (isset($config->organization_selection) && !empty($config->organization_selection)) {
  231. set_config('organization_selection', $config->organization_selection, 'auth/shibboleth');
  232. }
  233. set_config('logout_handler', $config->logout_handler, 'auth/shibboleth');
  234. set_config('logout_return_url', $config->logout_return_url, 'auth/shibboleth');
  235. set_config('login_name', $config->login_name, 'auth/shibboleth');
  236. set_config('convert_data', $config->convert_data, 'auth/shibboleth');
  237. set_config('auth_instructions', $config->auth_instructions, 'auth/shibboleth');
  238. set_config('changepasswordurl', $config->changepasswordurl, 'auth/shibboleth');
  239. // Overwrite alternative login URL if integrated WAYF is used
  240. if (isset($config->alt_login) && $config->alt_login == 'on'){
  241. set_config('alt_login', $config->alt_login, 'auth/shibboleth');
  242. set_config('alternateloginurl', $CFG->wwwroot.'/auth/shibboleth/login.php');
  243. } else {
  244. // Check if integrated WAYF was enabled and is now turned off
  245. // If it was and only then, reset the Moodle alternate URL
  246. if (isset($this->config->alt_login) and $this->config->alt_login == 'on'){
  247. set_config('alt_login', 'off', 'auth/shibboleth');
  248. set_config('alternateloginurl', '');
  249. }
  250. $config->alt_login = 'off';
  251. }
  252. // Check values and return false if something is wrong
  253. // Patch Anyware Technologies (14/05/07)
  254. if (($config->convert_data != '')&&(!file_exists($config->convert_data) || !is_readable($config->convert_data))){
  255. return false;
  256. }
  257. // Check if there is at least one entry in the IdP list
  258. if (isset($config->organization_selection) && empty($config->organization_selection) && isset($config->alt_login) && $config->alt_login == 'on'){
  259. return false;
  260. }
  261. return true;
  262. }
  263. /**
  264. * Cleans and returns first of potential many values (multi-valued attributes)
  265. *
  266. * @param string $string Possibly multi-valued attribute from Shibboleth
  267. */
  268. function get_first_string($string) {
  269. $list = explode( ';', $string);
  270. $clean_string = rtrim($list[0]);
  271. return $clean_string;
  272. }
  273. }
  274. /**
  275. * Sets the standard SAML domain cookie that is also used to preselect
  276. * the right entry on the local wayf
  277. *
  278. * @param IdP identifiere
  279. */
  280. function set_saml_cookie($selectedIDP) {
  281. if (isset($_COOKIE['_saml_idp']))
  282. {
  283. $IDPArray = generate_cookie_array($_COOKIE['_saml_idp']);
  284. }
  285. else
  286. {
  287. $IDPArray = array();
  288. }
  289. $IDPArray = appendCookieValue($selectedIDP, $IDPArray);
  290. setcookie ('_saml_idp', generate_cookie_value($IDPArray), time() + (100*24*3600));
  291. }
  292. /**
  293. * Prints the option elements for the select element of the drop down list
  294. *
  295. */
  296. function print_idp_list(){
  297. $config = get_config('auth/shibboleth');
  298. $IdPs = get_idp_list($config->organization_selection);
  299. if (isset($_COOKIE['_saml_idp'])){
  300. $idp_cookie = generate_cookie_array($_COOKIE['_saml_idp']);
  301. do {
  302. $selectedIdP = array_pop($idp_cookie);
  303. } while (!isset($IdPs[$selectedIdP]) && count($idp_cookie) > 0);
  304. } else {
  305. $selectedIdP = '-';
  306. }
  307. foreach($IdPs as $IdP => $data){
  308. if ($IdP == $selectedIdP){
  309. echo '<option value="'.$IdP.'" selected="selected">'.$data[0].'</option>';
  310. } else {
  311. echo '<option value="'.$IdP.'">'.$data[0].'</option>';
  312. }
  313. }
  314. }
  315. /**
  316. * Generate array of IdPs from Moodle Shibboleth settings
  317. *
  318. * @param string Text containing tuble/triple of IdP entityId, name and (optionally) session initiator
  319. * @return array Identifier of IdPs and their name/session initiator
  320. */
  321. function get_idp_list($organization_selection) {
  322. $idp_list = array();
  323. $idp_raw_list = explode("\n", $organization_selection);
  324. foreach ($idp_raw_list as $idp_line){
  325. $idp_data = explode(',', $idp_line);
  326. if (isset($idp_data[2]))
  327. {
  328. $idp_list[trim($idp_data[0])] = array(trim($idp_data[1]),trim($idp_data[2]));
  329. }
  330. elseif(isset($idp_data[1]))
  331. {
  332. $idp_list[trim($idp_data[0])] = array(trim($idp_data[1]));
  333. }
  334. }
  335. return $idp_list;
  336. }
  337. /**
  338. * Generates an array of IDPs using the cookie value
  339. *
  340. * @param string Value of SAML domain cookie
  341. * @return array Identifiers of IdPs
  342. */
  343. function generate_cookie_array($value) {
  344. // Decodes and splits cookie value
  345. $CookieArray = explode(' ', $value);
  346. $CookieArray = array_map('base64_decode', $CookieArray);
  347. return $CookieArray;
  348. }
  349. /**
  350. * Generate the value that is stored in the cookie using the list of IDPs
  351. *
  352. * @param array IdP identifiers
  353. * @return string SAML domain cookie value
  354. */
  355. function generate_cookie_value($CookieArray) {
  356. // Merges cookie content and encodes it
  357. $CookieArray = array_map('base64_encode', $CookieArray);
  358. $value = implode(' ', $CookieArray);
  359. return $value;
  360. }
  361. /**
  362. * Append a value to the array of IDPs
  363. *
  364. * @param string IdP identifier
  365. * @param array IdP identifiers
  366. * @return array IdP identifiers with appended IdP
  367. */
  368. function appendCookieValue($value, $CookieArray) {
  369. array_push($CookieArray, $value);
  370. $CookieArray = array_reverse($CookieArray);
  371. $CookieArray = array_unique($CookieArray);
  372. $CookieArray = array_reverse($CookieArray);
  373. return $CookieArray;
  374. }