Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
studip-sp.php 2.48 KiB
<?php
/*
 * studip-sp.php - Shibboleth authentication proxy for Stud.IP
 * Copyright (c) 2007-2011  Elmar Ludwig, Universitaet Osnabrueck
 *
 * Version: 1.3.1
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 */

// load configuration settings
require_once 'studip-sp-config.php';

if (isset($_REQUEST['target'])) {
    $token = generate_token();
    perform_redirect($_REQUEST['target'], $token);
} else if (isset($_SERVER['PATH_INFO'])) {
    $token = substr($_SERVER['PATH_INFO'], 1);
    validate_token($token);
}

function generate_token ()
{
    // get shibboleth user name
    $remote_user = $_SERVER['REMOTE_USER'] ?? null;

    $userdata = [];
    // import authentication information
    $userdata['username'] = $remote_user;

    foreach ($_SERVER as $key => $value) {
        if (preg_match('/^[a-zA-Z]+$/', $key)) {
            $key = strtolower($key);
            $userdata[$key] = $value;
        }
    }

    // create cache dir if necessary
    if (!file_exists(AUTH_DIR)) {
        mkdir(AUTH_DIR);
    }

    $token = md5(uniqid(rand(), true));
    if (!empty($userdata['username'])) {
        $auth = json_encode($userdata);
        file_put_contents(AUTH_DIR . '/' . $token, $auth);
    }
    return $token;
}

function perform_redirect ($target, $token)
{
    global $service_urls;

    // drop query string from service URL
    [$service_url] = explode('?', $target);

    // check for valid service_url
    foreach ($service_urls as $url) {
        if (strncasecmp($service_url, $url, strlen($url)) == 0) {
            $target .= strpos($target, '?') === false ? '?' : '&';
            $target .= 'token='.$token;

            header('Location: '.$target);
            echo '<html><body></body></html>';
            return;
        }
    }

    header('HTTP/1.1 403 Forbidden');
    echo '<html><head>'.
         '<title>Invalid Service URL</title>'.
         '</head><body>'.
         '<h2>Invalid Service URL</h2>'.
         '<p>The service <tt>'.htmlspecialchars($service_url).
         '</tt> is not allowed to use this proxy.</p>'.
         '</body></html>';
}

function validate_token ($token)
{
    $file = AUTH_DIR.'/'.$token;

    // check for cached authentication data
    if (preg_match('/^[0-9a-f]+$/', $token) && file_exists($file)) {
        readfile($file);
        unlink($file);
    }
}