Skip to content

Commit

Permalink
allow saving/loading of kerberos tickets
Browse files Browse the repository at this point in the history
  • Loading branch information
icewind1991 committed Aug 9, 2023
1 parent f944fae commit a103d9d
Show file tree
Hide file tree
Showing 7 changed files with 186 additions and 89 deletions.
5 changes: 4 additions & 1 deletion example-apache-kerberos.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
<?php

use Icewind\SMB\KerberosTicket;

require('vendor/autoload.php');

if (php_sapi_name() == "cli") {
Expand All @@ -10,7 +12,8 @@
$host = 'krb.domain.test';
$share = 'netlogon';

$auth = new \Icewind\SMB\KerberosApacheAuth();
$auth = new \Icewind\SMB\KerberosAuth();
$auth->setTicket(KerberosTicket::fromEnv());
$serverFactory = new \Icewind\SMB\ServerFactory();

$server = $serverFactory->createServer($host, $auth);
Expand Down
3 changes: 3 additions & 0 deletions psalm.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
xmlns="https://getpsalm.org/schema/config"
xsi:schemaLocation="https://getpsalm.org/schema/config vendor/vimeo/psalm/config.xsd"
>
<stubs>
<file name="tests/krb.phpstub" preloadClasses="true"/>
</stubs>
<projectFiles>
<directory name="src" />
<ignoreFiles>
Expand Down
28 changes: 28 additions & 0 deletions src/Exception/InvalidTicket.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);
/**
* @copyright Copyright (c) 2022 Robin Appelman <[email protected]>
*
* @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 Icewind\SMB\Exception;

class InvalidTicket extends Exception {

}
102 changes: 14 additions & 88 deletions src/KerberosApacheAuth.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,114 +23,40 @@

use Icewind\SMB\Exception\DependencyException;
use Icewind\SMB\Exception\Exception;
use Icewind\SMB\Exception\InvalidTicket;

/**
* Use existing kerberos ticket to authenticate and reuse the apache ticket cache (mod_auth_kerb)
*
* @deprecated Use `KerberosAuth` with `$auth->setTicket(KerberosTicket::fromEnv())` instead
*/
class KerberosApacheAuth extends KerberosAuth implements IAuth {
/** @var string */
private $ticketPath = "";

/** @var bool */
private $init = false;

/** @var string|false */
private $ticketName;

public function __construct() {
$this->ticketName = getenv("KRB5CCNAME");
public function getTicket(): KerberosTicket {
if ($this->ticket === null) {
$ticket = KerberosTicket::fromEnv();
if ($ticket === null) {
throw new InvalidTicket("No ticket found in environment");
}
$this->ticket = $ticket;
}
return $this->ticket;
}


/**
* Copy the ticket to a temporary location and use that ticket for authentication
*
* @return void
*/
public function copyTicket(): void {
if (!$this->checkTicket()) {
return;
}
$krb5 = new \KRB5CCache();
$krb5->open($this->ticketName);
$tmpFilename = tempnam("/tmp", "krb5cc_php_");
$tmpCacheFile = "FILE:" . $tmpFilename;
$krb5->save($tmpCacheFile);
$this->ticketPath = $tmpFilename;
$this->ticketName = $tmpCacheFile;
}

/**
* Pass the ticket to smbclient by memory instead of path
*
* @return void
*/
public function passTicketFromMemory(): void {
if (!$this->checkTicket()) {
return;
}
$krb5 = new \KRB5CCache();
$krb5->open($this->ticketName);
$this->ticketName = (string)$krb5->getName();
$this->ticket = KerberosTicket::load($this->getTicket()->save());
}

/**
* Check if a valid kerberos ticket is present
*
* @return bool
* @psalm-assert-if-true string $this->ticketName
*/
public function checkTicket(): bool {
//read apache kerberos ticket cache
if (!$this->ticketName) {
return false;
}

$krb5 = new \KRB5CCache();
$krb5->open($this->ticketName);
/** @psalm-suppress MixedArgument */
return count($krb5->getEntries()) > 0;
}

private function init(): void {
if ($this->init) {
return;
}
$this->init = true;
// inspired by https://git.typo3.org/TYPO3CMS/Extensions/fal_cifs.git

if (!extension_loaded("krb5")) {
// https://pecl.php.net/package/krb5
throw new DependencyException('Ensure php-krb5 is installed.');
}

//read apache kerberos ticket cache
if (!$this->checkTicket()) {
throw new Exception('No kerberos ticket cache environment variable (KRB5CCNAME) found.');
}

// note that even if the ticketname is the value we got from `getenv("KRB5CCNAME")` we still need to set the env variable ourselves
// this is because `getenv` also reads the variables passed from the SAPI (apache-php) and we need to set the variable in the OS's env
putenv("KRB5CCNAME=" . $this->ticketName);
}

public function getExtraCommandLineArguments(): string {
$this->init();
return parent::getExtraCommandLineArguments();
}

public function setExtraSmbClientOptions($smbClientState): void {
$this->init();
try {
parent::setExtraSmbClientOptions($smbClientState);
} catch (Exception $e) {
// suppress
}
}

public function __destruct() {
if (!empty($this->ticketPath) && file_exists($this->ticketPath) && is_file($this->ticketPath)) {
unlink($this->ticketPath);
}
return $this->getTicket()->isValid();
}
}
25 changes: 25 additions & 0 deletions src/KerberosAuth.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,17 @@
* Use existing kerberos ticket to authenticate
*/
class KerberosAuth implements IAuth {
/** @var ?KerberosTicket */
protected $ticket = null;

public function getTicket(): ?KerberosTicket {
return $this->ticket;
}

public function setTicket(KerberosTicket $ticket): void {
$this->ticket = $ticket;
}

public function getUsername(): ?string {
return 'dummy';
}
Expand All @@ -39,11 +50,25 @@ public function getPassword(): ?string {
return null;
}

private function setEnv():void {
$ticket = $this->getTicket();
if ($ticket) {
$ticket->validate();

// note that even if the ticket name is the value we got from `getenv("KRB5CCNAME")` we still need to set the env variable ourselves
// this is because `getenv` also reads the variables passed from the SAPI (apache-php) and we need to set the variable in the OS's env
putenv("KRB5CCNAME=" . $ticket->getCacheName());
}
}

public function getExtraCommandLineArguments(): string {
$this->setEnv();
return '-k';
}

public function setExtraSmbClientOptions($smbClientState): void {
$this->setEnv();

$success = (bool)smbclient_option_set($smbClientState, SMBCLIENT_OPT_USE_KERBEROS, true);
$success = $success && smbclient_option_set($smbClientState, SMBCLIENT_OPT_FALLBACK_AFTER_KERBEROS, false);

Expand Down
100 changes: 100 additions & 0 deletions src/KerberosTicket.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
<?php

declare(strict_types=1);
/**
* @copyright Copyright (c) 2022 Robin Appelman <[email protected]>
*
* @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 Icewind\SMB;

use Icewind\SMB\Exception\InvalidTicket;
use KRB5CCache;

class KerberosTicket {
/** @var KRB5CCache */
private $krb5;
/** @var string */
private $cacheName;

public function __construct(KRB5CCache $krb5, string $cacheName) {
$this->krb5 = $krb5;
$this->cacheName = $cacheName;
}

public function getCacheName(): string {
return $this->cacheName;
}

public function getName(): string{
return $this->krb5->getName();
}

public function isValid(): bool {
return count($this->krb5->getEntries()) > 0;
}

public function validate(): void {
if (!$this->isValid()) {
throw new InvalidTicket("No kerberos ticket found.");
}
}

/**
* Load the ticket from the cache specified by the KRB5CCNAME variable.
*
* @return KerberosTicket|null
*/
public static function fromEnv(): ?KerberosTicket {
$ticketName = getenv("KRB5CCNAME");
if (!$ticketName) {
return null;
}
$krb5 = new KRB5CCache();
$krb5->open($ticketName);
return new KerberosTicket($krb5, $ticketName);
}

public static function load(string $ticket): KerberosTicket {
$tmpFilename = tempnam(sys_get_temp_dir(), "krb5cc_php_");
file_put_contents($tmpFilename, $ticket);
register_shutdown_function(function () use ($tmpFilename) {
if (file_exists($tmpFilename)) {
unlink($tmpFilename);
}
});

$ticketName = "FILE:" . $tmpFilename;
$krb5 = new KRB5CCache();
$krb5->open($ticketName);
return new KerberosTicket($krb5, $ticketName);
}

public function save(): string {
if (substr($this->cacheName, 0, 5) === 'FILE:') {
$ticket = file_get_contents(substr($this->cacheName, 5));
} else {
$tmpFilename = tempnam(sys_get_temp_dir(), "krb5cc_php_");
$tmpCacheFile = "FILE:" . $tmpFilename;
$this->krb5->save($tmpCacheFile);
$ticket = file_get_contents($tmpFilename);
unlink($tmpFilename);
}
return $ticket;
}
}
12 changes: 12 additions & 0 deletions tests/krb.phpstub
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

class KRB5CCache {
public function getEntries(): array { return [];}
public function getName(): string {return "";}
public function initKeytab(string $principal, string $keytab, array $flags = []): void {}
public function initPassword(string $principal, string $password, array $flags = []): void {}
public function isValid(): bool {return false;}
public function open(string $source): void {}
public function save(string $destination): void {}
public function setConfig(string $destination): void {}
}

0 comments on commit a103d9d

Please sign in to comment.