Skip to content

Commit

Permalink
Add support for saving kerberos sso ticket in session for later reuse
Browse files Browse the repository at this point in the history
Signed-off-by: Robin Appelman <robin@icewind.nl>
  • Loading branch information
icewind1991 committed Sep 1, 2023
1 parent 0daaf07 commit 7aed00a
Show file tree
Hide file tree
Showing 15 changed files with 253 additions and 15 deletions.
44 changes: 44 additions & 0 deletions .github/workflows/smb-kerberos.yml
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,47 @@ jobs:
FILEPATH=$(docker exec --user 33 apache ./occ log:file | grep "Log file:" | cut -d' ' -f3)
echo "$FILEPATH:"
docker exec --user 33 apache cat $FILEPATH
smb-kerberos-session-tests:
runs-on: ubuntu-latest

if: ${{ github.repository_owner != 'nextcloud-gmbh' }}

name: smb-kerberos-sso

steps:
- name: Checkout server
uses: actions/checkout@v3
with:
submodules: true
- name: Checkout user_saml
uses: actions/checkout@v3
with:
repository: nextcloud/user_saml
path: apps/user_saml
ref: event-dispatcher
- name: Pull images
run: |
docker pull ghcr.io/icewind1991/samba-krb-test-dc
docker pull ghcr.io/icewind1991/samba-krb-test-apache
docker pull ghcr.io/icewind1991/samba-krb-test-client
docker tag ghcr.io/icewind1991/samba-krb-test-dc icewind1991/samba-krb-test-dc
docker tag ghcr.io/icewind1991/samba-krb-test-apache icewind1991/samba-krb-test-apache
docker tag ghcr.io/icewind1991/samba-krb-test-client icewind1991/samba-krb-test-client
- name: Setup AD-DC
run: |
DC_IP=$(apps/files_external/tests/sso-setup/start-dc.sh)
apps/files_external/tests/sso-setup/start-apache.sh $DC_IP $PWD -v $PWD/apps/files_external/tests/sso-setup/apache-session.conf:/etc/apache2/sites-enabled/000-default.conf
echo "DC_IP=$DC_IP" >> $GITHUB_ENV
- name: Set up Nextcloud
run: |
apps/files_external/tests/sso-setup/setup-sso-nc.sh smb::kerberos_sso_session
- name: Test SSO
run: |
apps/files_external/tests/sso-setup/test-sso-smb-session.sh ${{ env.DC_IP }}
- name: Show logs
if: failure()
run: |
FILEPATH=$(docker exec --user 33 apache ./occ log:file | grep "Log file:" | cut -d' ' -f3)
echo "$FILEPATH:"
docker exec --user 33 apache cat $FILEPATH
2 changes: 2 additions & 0 deletions apps/files_external/composer/composer/autoload_classmap.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
'OCA\\Files_External\\Lib\\Auth\\PublicKey\\RSAPrivateKey' => $baseDir . '/../lib/Lib/Auth/PublicKey/RSAPrivateKey.php',
'OCA\\Files_External\\Lib\\Auth\\SMB\\KerberosApacheAuth' => $baseDir . '/../lib/Lib/Auth/SMB/KerberosApacheAuth.php',
'OCA\\Files_External\\Lib\\Auth\\SMB\\KerberosAuth' => $baseDir . '/../lib/Lib/Auth/SMB/KerberosAuth.php',
'OCA\\Files_External\\Lib\\Auth\\SMB\\KerberosSsoSession' => $baseDir . '/../lib/Lib/Auth/SMB/KerberosSsoSession.php',
'OCA\\Files_External\\Lib\\Backend\\AmazonS3' => $baseDir . '/../lib/Lib/Backend/AmazonS3.php',
'OCA\\Files_External\\Lib\\Backend\\Backend' => $baseDir . '/../lib/Lib/Backend/Backend.php',
'OCA\\Files_External\\Lib\\Backend\\DAV' => $baseDir . '/../lib/Lib/Backend/DAV.php',
Expand Down Expand Up @@ -94,6 +95,7 @@
'OCA\\Files_External\\Lib\\Storage\\SMB' => $baseDir . '/../lib/Lib/Storage/SMB.php',
'OCA\\Files_External\\Lib\\Storage\\StreamWrapper' => $baseDir . '/../lib/Lib/Storage/StreamWrapper.php',
'OCA\\Files_External\\Lib\\Storage\\Swift' => $baseDir . '/../lib/Lib/Storage/Swift.php',
'OCA\\Files_External\\Lib\\TicketSaveMiddleware' => $baseDir . '/../lib/Lib/TicketSaveMiddleware.php',
'OCA\\Files_External\\Lib\\VisibilityTrait' => $baseDir . '/../lib/Lib/VisibilityTrait.php',
'OCA\\Files_External\\Listener\\GroupDeletedListener' => $baseDir . '/../lib/Listener/GroupDeletedListener.php',
'OCA\\Files_External\\Listener\\LoadAdditionalListener' => $baseDir . '/../lib/Listener/LoadAdditionalListener.php',
Expand Down
2 changes: 2 additions & 0 deletions apps/files_external/composer/composer/autoload_static.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ class ComposerStaticInitFiles_External
'OCA\\Files_External\\Lib\\Auth\\PublicKey\\RSAPrivateKey' => __DIR__ . '/..' . '/../lib/Lib/Auth/PublicKey/RSAPrivateKey.php',
'OCA\\Files_External\\Lib\\Auth\\SMB\\KerberosApacheAuth' => __DIR__ . '/..' . '/../lib/Lib/Auth/SMB/KerberosApacheAuth.php',
'OCA\\Files_External\\Lib\\Auth\\SMB\\KerberosAuth' => __DIR__ . '/..' . '/../lib/Lib/Auth/SMB/KerberosAuth.php',
'OCA\\Files_External\\Lib\\Auth\\SMB\\KerberosSsoSession' => __DIR__ . '/..' . '/../lib/Lib/Auth/SMB/KerberosSsoSession.php',
'OCA\\Files_External\\Lib\\Backend\\AmazonS3' => __DIR__ . '/..' . '/../lib/Lib/Backend/AmazonS3.php',
'OCA\\Files_External\\Lib\\Backend\\Backend' => __DIR__ . '/..' . '/../lib/Lib/Backend/Backend.php',
'OCA\\Files_External\\Lib\\Backend\\DAV' => __DIR__ . '/..' . '/../lib/Lib/Backend/DAV.php',
Expand Down Expand Up @@ -109,6 +110,7 @@ class ComposerStaticInitFiles_External
'OCA\\Files_External\\Lib\\Storage\\SMB' => __DIR__ . '/..' . '/../lib/Lib/Storage/SMB.php',
'OCA\\Files_External\\Lib\\Storage\\StreamWrapper' => __DIR__ . '/..' . '/../lib/Lib/Storage/StreamWrapper.php',
'OCA\\Files_External\\Lib\\Storage\\Swift' => __DIR__ . '/..' . '/../lib/Lib/Storage/Swift.php',
'OCA\\Files_External\\Lib\\TicketSaveMiddleware' => __DIR__ . '/..' . '/../lib/Lib/TicketSaveMiddleware.php',
'OCA\\Files_External\\Lib\\VisibilityTrait' => __DIR__ . '/..' . '/../lib/Lib/VisibilityTrait.php',
'OCA\\Files_External\\Listener\\GroupDeletedListener' => __DIR__ . '/..' . '/../lib/Listener/GroupDeletedListener.php',
'OCA\\Files_External\\Listener\\LoadAdditionalListener' => __DIR__ . '/..' . '/../lib/Listener/LoadAdditionalListener.php',
Expand Down
4 changes: 4 additions & 0 deletions apps/files_external/lib/AppInfo/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
use OCA\Files_External\Lib\Auth\PublicKey\RSAPrivateKey;
use OCA\Files_External\Lib\Auth\SMB\KerberosApacheAuth;
use OCA\Files_External\Lib\Auth\SMB\KerberosAuth;
use OCA\Files_External\Lib\Auth\SMB\KerberosSsoSession;
use OCA\Files_External\Lib\Backend\AmazonS3;
use OCA\Files_External\Lib\Backend\DAV;
use OCA\Files_External\Lib\Backend\FTP;
Expand All @@ -62,6 +63,7 @@
use OCA\Files_External\Lib\Backend\Swift;
use OCA\Files_External\Lib\Config\IAuthMechanismProvider;
use OCA\Files_External\Lib\Config\IBackendProvider;
use OCA\Files_External\Lib\TicketSaveMiddleware;
use OCA\Files_External\Listener\GroupDeletedListener;
use OCA\Files_External\Listener\LoadAdditionalListener;
use OCA\Files_External\Listener\UserDeletedListener;
Expand Down Expand Up @@ -95,6 +97,7 @@ public function register(IRegistrationContext $context): void {
$context->registerEventListener(UserDeletedEvent::class, UserDeletedListener::class);
$context->registerEventListener(GroupDeletedEvent::class, GroupDeletedListener::class);
$context->registerEventListener(LoadAdditionalScriptsEvent::class, LoadAdditionalListener::class);
$context->registerMiddleware(TicketSaveMiddleware::class, true);
}

public function boot(IBootContext $context): void {
Expand Down Expand Up @@ -176,6 +179,7 @@ public function getAuthMechanisms() {
$container->get(AccessKey::class),
$container->get(KerberosAuth::class),
$container->get(KerberosApacheAuth::class),
$container->get(KerberosSsoSession::class),
];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public function __construct(IL10N $l, IStore $credentialsStore) {
$this
->setIdentifier('smb::kerberosapache')
->setScheme(self::SCHEME_SMB)
->setText($l->t('Kerberos ticket Apache mode'))
->setText($l->t('Kerberos ticket SSO'))
->addParameter($realm);
$this->credentialsStore = $credentialsStore;
}
Expand Down
68 changes: 68 additions & 0 deletions apps/files_external/lib/Lib/Auth/SMB/KerberosSsoSession.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?php

/**
* @copyright Copyright (c) 2018 Robin Appelman <robin@icewind.nl>
*
* @author Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/

namespace OCA\Files_External\Lib\Auth\SMB;

use Icewind\SMB\KerberosTicket;
use OCA\Files_External\Lib\Auth\AuthMechanism;
use OCA\Files_External\Lib\DefinitionParameter;
use OCA\Files_External\Lib\InsufficientDataForMeaningfulAnswerException;
use OCP\IL10N;
use OCP\ISession;

class KerberosSsoSession extends AuthMechanism {

Check notice

Code scanning / Psalm

PropertyNotSetInConstructor Note

Property OCA\Files_External\Lib\Auth\SMB\KerberosSsoSession::$scheme is not defined in constructor of OCA\Files_External\Lib\Auth\SMB\KerberosSsoSession or in any private or final methods called in the constructor
private ISession $session;

public function __construct(IL10N $l, ISession $session) {
$realm = new DefinitionParameter('default_realm', 'Default realm');
$realm
->setType(DefinitionParameter::VALUE_TEXT)
->setFlag(DefinitionParameter::FLAG_OPTIONAL)
->setTooltip($l->t('Kerberos default realm, defaults to "WORKGROUP"'));
$this
->setIdentifier('smb::kerberos_sso_session')
->setScheme(self::SCHEME_SMB)
->setText($l->t('Kerberos ticket SSO, save in session'))
->addParameter($realm);
$this->session = $session;
}

public function getTicket(): KerberosTicket {
try {
$envTicket = KerberosTicket::fromEnv();
} catch (\Exception $e) {
$envTicket = null;
}
if ($envTicket) {
$this->session->set('kerberos_ticket', base64_encode($envTicket->save()));
return $envTicket;
}

$savedTicket = $this->session->get('kerberos_ticket');
if (!$savedTicket) {
throw new InsufficientDataForMeaningfulAnswerException('No kerberos ticket saved');
}
return KerberosTicket::load(base64_decode($savedTicket));
}
}
17 changes: 14 additions & 3 deletions apps/files_external/lib/Lib/Backend/SMB.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,11 @@
use Icewind\SMB\BasicAuth;
use Icewind\SMB\KerberosApacheAuth;
use Icewind\SMB\KerberosAuth;
use Icewind\SMB\KerberosTicket;
use OCA\Files_External\Lib\Auth\AuthMechanism;
use OCA\Files_External\Lib\Auth\Password\Password;
use OCA\Files_External\Lib\Auth\SMB\KerberosApacheAuth as KerberosApacheAuthMechanism;
use OCA\Files_External\Lib\Auth\SMB\KerberosSsoSession;
use OCA\Files_External\Lib\DefinitionParameter;
use OCA\Files_External\Lib\InsufficientDataForMeaningfulAnswerException;
use OCA\Files_External\Lib\LegacyDependencyCheckPolyfill;
Expand Down Expand Up @@ -89,16 +91,25 @@ public function manipulateStorageConfig(StorageConfig &$storage, IUser $user = n
case 'smb::kerberos':
$smbAuth = new KerberosAuth();
break;
case 'smb::kerberos_sso_session':
if (!$auth instanceof KerberosSsoSession) {
throw new \InvalidArgumentException('invalid authentication backend');
}
$smbAuth = new KerberosAuth();
$smbAuth->setTicket($auth->getTicket());
break;
case 'smb::kerberosapache':
if (!$auth instanceof KerberosApacheAuthMechanism) {
throw new \InvalidArgumentException('invalid authentication backend');
}
$credentialsStore = $auth->getCredentialsStore();
$kerbAuth = new KerberosApacheAuth();
$ticket = KerberosTicket::fromEnv();
// check if a kerberos ticket is available, else fallback to session credentials
if ($kerbAuth->checkTicket()) {
if ($ticket && $ticket->isValid()) {
$kerbAuth = new KerberosAuth();
$kerbAuth->setTicket($ticket);
$smbAuth = $kerbAuth;
} else {
$credentialsStore = $auth->getCredentialsStore();
try {
$credentials = $credentialsStore->getLoginCredentials();
$user = $credentials->getLoginName();
Expand Down
45 changes: 45 additions & 0 deletions apps/files_external/lib/Lib/TicketSaveMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/

namespace OCA\Files_External\Lib;

use Icewind\SMB\KerberosTicket;
use OCP\AppFramework\Http\Response;
use OCP\AppFramework\Middleware;
use OCP\ISession;

class TicketSaveMiddleware extends Middleware {
private ISession $session;

public function __construct(ISession $session) {
$this->session = $session;
}

public function afterController($controller, $methodName, Response $response) {
$ticket = KerberosTicket::fromEnv();
if ($ticket && $ticket->isValid()) {
$this->session->set('kerberos_ticket', base64_encode($ticket->save()));
}
return $response;
}
}
19 changes: 19 additions & 0 deletions apps/files_external/tests/sso-setup/apache-session.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html

<Location /index.php/apps/user_saml/saml/login>
AuthType Kerberos
AuthName "Kerberos authenticated intranet"
KrbAuthRealms DOMAIN.TEST
KrbServiceName HTTP/httpd.domain.test
Krb5Keytab /shared/httpd.keytab
KrbMethodNegotiate On
KrbMethodK5Passwd On
KrbSaveCredentials On
require valid-user
</Location>

ErrorLog /shared/apache-error.log
CustomLog /shared/apache-access.log combined
</VirtualHost>
10 changes: 10 additions & 0 deletions apps/files_external/tests/sso-setup/run.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#!/usr/bin/env bash
set -e

SCRIPT_DIR="${0%/*}"

DC_IP=$(apps/files_external/tests/sso-setup/start-dc.sh)
apps/files_external/tests/sso-setup/start-apache.sh "$DC_IP" "$PWD" -v "$PWD/$SCRIPT_DIR"/apache-session.conf:/etc/apache2/sites-enabled/000-default.conf
apps/files_external/tests/sso-setup/setup-sso-nc.sh smb::kerberos_sso_session

apps/files_external/tests/sso-setup/test-sso-smb-session.sh "$DC_IP"
4 changes: 3 additions & 1 deletion apps/files_external/tests/sso-setup/setup-sso-nc.sh
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#!/usr/bin/env bash
set -e

AUTH=${1:-"smb::kerberosapache"}

docker exec --user 33 apache ./occ maintenance:install --verbose --database=sqlite --database-name=nextcloud --database-host=127.0.0.1 --database-user=root --database-pass=rootpassword --admin-user admin --admin-pass password
docker exec --user 33 apache ./occ config:system:set trusted_domains 1 --value 'httpd.domain.test'

Expand All @@ -15,7 +17,7 @@ docker exec -e OC_PASS=test --user 33 apache ./occ user:add 'testuser@DOMAIN.TES

# setup external storage
docker exec --user 33 apache ./occ app:enable files_external --force
docker exec --user 33 apache ./occ files_external:create smb smb smb::kerberosapache
docker exec --user 33 apache ./occ files_external:create smb smb "$AUTH"
docker exec --user 33 apache ./occ files_external:config 1 host krb.domain.test
docker exec --user 33 apache ./occ files_external:config 1 share netlogon
docker exec --user 33 apache ./occ files_external:list
12 changes: 9 additions & 3 deletions apps/files_external/tests/sso-setup/start-apache.sh
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,18 @@ SCRIPT_DIR="${0%/*}"

docker rm -f apache 2>/dev/null > /dev/null

docker run -d --name apache -v $2:/var/www/html -v /var/www/html/data -v /var/www/html/config -v /var/www/html/extra-apps -v /tmp/shared:/shared --dns $1 --hostname httpd.domain.test icewind1991/samba-krb-test-apache 1>&2
DC_IP="$1"
DIR="$2"
shift 2

# shellcheck disable=SC2068
docker run -d --name apache -v "$DIR":/var/www/html -v /var/www/html/data -v /var/www/html/config -v /var/www/html/extra-apps -v /tmp/shared:/shared \
--add-host host.docker.internal:host-gateway --dns "$DC_IP" --hostname httpd.domain.test $@ icewind1991/samba-krb-test-apache 1>&2
APACHE_IP=$(docker inspect apache --format '{{.NetworkSettings.IPAddress}}')
docker exec apache chown 33 /var/www/html/config /var/www/html/data /var/www/html/extra-apps
docker cp "$SCRIPT_DIR/apps.config.php" apache:/var/www/html/config/apps.config.php

# add the dns record for apache
docker exec dc samba-tool dns add krb.domain.test domain.test httpd A $APACHE_IP -U administrator --password=passwOrd1 1>&2
docker exec dc samba-tool dns add krb.domain.test domain.test httpd A "$APACHE_IP" -U administrator --password=passwOrd1 1>&2

echo $APACHE_IP
echo "$APACHE_IP"
8 changes: 4 additions & 4 deletions apps/files_external/tests/sso-setup/start-dc.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@
set -e

function getContainerHealth {
docker inspect --format "{{.State.Health.Status}}" $1
docker inspect --format "{{.State.Health.Status}}" "$1"
}

function waitContainer {
while STATUS=$(getContainerHealth $1); [ $STATUS != "healthy" ]; do
if [ $STATUS == "unhealthy" ]; then
while STATUS=$(getContainerHealth "$1"); [ "$STATUS" != "healthy" ]; do
if [ "$STATUS" == "unhealthy" ]; then
echo "Failed!" 1>&2
exit -1
exit 1
fi
printf . 1>&2
lf=$'\n'
Expand Down
25 changes: 25 additions & 0 deletions apps/files_external/tests/sso-setup/test-sso-smb-session.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#!/usr/bin/env bash
set -e

DC_IP="$1"
SCRIPT_DIR="${0%/*}"

echo -n "Checking that we can authenticate using kerberos: "
LOGIN_CONTENT=$("$SCRIPT_DIR/client-cmd.sh" "$DC_IP" curl -i -s -c /shared/cookie -i -s --negotiate -u testuser@DOMAIN.TEST: --delegation always 'http://httpd.domain.test/index.php/apps/user_saml/saml/login?originalUrl=success&XDEBUG_SESSION_START=1')
if [[ "$LOGIN_CONTENT" =~ "Location: success" ]]; then
echo "✔️"
else
echo ""
exit 1
fi

echo -n "Getting test with session file: "
CONTENT=$("$SCRIPT_DIR/client-cmd.sh" "$DC_IP" curl -s -b /shared/cookie 'http://httpd.domain.test/remote.php/webdav/smb/test.txt?XDEBUG_SESSION_START=1')
CONTENT=$(echo "$CONTENT" | head -n 1 | tr -d '[:space:]')

if [[ $CONTENT == "testfile" ]]; then
echo "✔️"
else
echo ""
exit 1
fi
Loading

0 comments on commit 7aed00a

Please sign in to comment.