Change how API keys are validated (#771)
This commit is contained in:
parent
df7a857929
commit
285485d7b0
24 changed files with 774 additions and 383 deletions
|
@ -1,27 +1,4 @@
|
|||
<?php
|
||||
/**
|
||||
* Pterodactyl - Panel
|
||||
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>
|
||||
* Some Modifications (c) 2015 Dylan Seidt <dylan.seidt@gmail.com>.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
* SOFTWARE.
|
||||
*/
|
||||
|
||||
namespace Pterodactyl\Http\Controllers\Base;
|
||||
|
||||
|
@ -120,7 +97,7 @@ class APIController extends Controller
|
|||
'memo' => $request->input('memo'),
|
||||
], $request->input('permissions', []), $adminPermissions);
|
||||
|
||||
$this->alert->success(trans('base.api.index.keypair_created', ['token' => $secret]))->flash();
|
||||
$this->alert->success(trans('base.api.index.keypair_created'))->flash();
|
||||
|
||||
return redirect()->route('account.api');
|
||||
}
|
||||
|
@ -136,7 +113,7 @@ class APIController extends Controller
|
|||
{
|
||||
$this->repository->deleteWhere([
|
||||
['user_id', '=', $request->user()->id],
|
||||
['public', '=', $key],
|
||||
['token', '=', $key],
|
||||
]);
|
||||
|
||||
return response('', 204);
|
||||
|
|
|
@ -11,17 +11,20 @@ use Pterodactyl\Http\Middleware\EncryptCookies;
|
|||
use Pterodactyl\Http\Middleware\VerifyCsrfToken;
|
||||
use Pterodactyl\Http\Middleware\VerifyReCaptcha;
|
||||
use Pterodactyl\Http\Middleware\AdminAuthenticate;
|
||||
use Pterodactyl\Http\Middleware\HMACAuthorization;
|
||||
use Illuminate\Routing\Middleware\ThrottleRequests;
|
||||
use Pterodactyl\Http\Middleware\LanguageMiddleware;
|
||||
use Illuminate\Foundation\Http\Kernel as HttpKernel;
|
||||
use Pterodactyl\Http\Middleware\API\AuthenticateKey;
|
||||
use Illuminate\Routing\Middleware\SubstituteBindings;
|
||||
use Pterodactyl\Http\Middleware\AccessingValidServer;
|
||||
use Pterodactyl\Http\Middleware\API\SetSessionDriver;
|
||||
use Illuminate\View\Middleware\ShareErrorsFromSession;
|
||||
use Pterodactyl\Http\Middleware\RedirectIfAuthenticated;
|
||||
use Illuminate\Auth\Middleware\AuthenticateWithBasicAuth;
|
||||
use Pterodactyl\Http\Middleware\API\AuthenticateIPAccess;
|
||||
use Pterodactyl\Http\Middleware\Daemon\DaemonAuthenticate;
|
||||
use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
|
||||
use Pterodactyl\Http\Middleware\API\HasPermissionToResource;
|
||||
use Pterodactyl\Http\Middleware\Server\AuthenticateAsSubuser;
|
||||
use Pterodactyl\Http\Middleware\Server\SubuserBelongsToServer;
|
||||
use Pterodactyl\Http\Middleware\RequireTwoFactorAuthentication;
|
||||
|
@ -42,10 +45,6 @@ class Kernel extends HttpKernel
|
|||
EncryptCookies::class,
|
||||
AddQueuedCookiesToResponse::class,
|
||||
TrimStrings::class,
|
||||
|
||||
/*
|
||||
* Custom middleware applied to all routes.
|
||||
*/
|
||||
TrustProxies::class,
|
||||
];
|
||||
|
||||
|
@ -66,9 +65,11 @@ class Kernel extends HttpKernel
|
|||
RequireTwoFactorAuthentication::class,
|
||||
],
|
||||
'api' => [
|
||||
HMACAuthorization::class,
|
||||
'throttle:60,1',
|
||||
'bindings',
|
||||
SubstituteBindings::class,
|
||||
SetSessionDriver::class,
|
||||
AuthenticateKey::class,
|
||||
AuthenticateIPAccess::class,
|
||||
],
|
||||
'daemon' => [
|
||||
SubstituteBindings::class,
|
||||
|
@ -95,6 +96,9 @@ class Kernel extends HttpKernel
|
|||
'bindings' => SubstituteBindings::class,
|
||||
'recaptcha' => VerifyReCaptcha::class,
|
||||
|
||||
// API specific middleware.
|
||||
'api..user_level' => HasPermissionToResource::class,
|
||||
|
||||
// Server specific middleware (used for authenticating access to resources)
|
||||
//
|
||||
// These are only used for individual server authentication, and not gloabl
|
||||
|
|
40
app/Http/Middleware/API/AuthenticateIPAccess.php
Normal file
40
app/Http/Middleware/API/AuthenticateIPAccess.php
Normal file
|
@ -0,0 +1,40 @@
|
|||
<?php
|
||||
|
||||
namespace Pterodactyl\Http\Middleware\API;
|
||||
|
||||
use Closure;
|
||||
use IPTools\IP;
|
||||
use IPTools\Range;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
|
||||
|
||||
class AuthenticateIPAccess
|
||||
{
|
||||
/**
|
||||
* Determine if a request IP has permission to access the API.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param \Closure $next
|
||||
* @return mixed
|
||||
*
|
||||
* @throws \Exception
|
||||
* @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
|
||||
*/
|
||||
public function handle(Request $request, Closure $next)
|
||||
{
|
||||
$model = $request->attributes->get('api_key');
|
||||
|
||||
if (is_null($model->allowed_ips) || empty($model->allowed_ips)) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
$find = new IP($request->ip());
|
||||
foreach ($model->allowed_ips as $ip) {
|
||||
if (Range::parse($ip)->contains($find)) {
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
|
||||
throw new AccessDeniedHttpException('This IP address does not have permission to access the API using these credentials.');
|
||||
}
|
||||
}
|
68
app/Http/Middleware/API/AuthenticateKey.php
Normal file
68
app/Http/Middleware/API/AuthenticateKey.php
Normal file
|
@ -0,0 +1,68 @@
|
|||
<?php
|
||||
|
||||
namespace Pterodactyl\Http\Middleware\API;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Auth\AuthManager;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
use Pterodactyl\Exceptions\Repository\RecordNotFoundException;
|
||||
use Pterodactyl\Contracts\Repository\ApiKeyRepositoryInterface;
|
||||
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
|
||||
|
||||
class AuthenticateKey
|
||||
{
|
||||
/**
|
||||
* @var \Illuminate\Auth\AuthManager
|
||||
*/
|
||||
private $auth;
|
||||
|
||||
/**
|
||||
* @var \Pterodactyl\Contracts\Repository\ApiKeyRepositoryInterface
|
||||
*/
|
||||
private $repository;
|
||||
|
||||
/**
|
||||
* AuthenticateKey constructor.
|
||||
*
|
||||
* @param \Pterodactyl\Contracts\Repository\ApiKeyRepositoryInterface $repository
|
||||
* @param \Illuminate\Auth\AuthManager $auth
|
||||
*/
|
||||
public function __construct(
|
||||
ApiKeyRepositoryInterface $repository,
|
||||
AuthManager $auth
|
||||
) {
|
||||
$this->auth = $auth;
|
||||
$this->repository = $repository;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle an API request by verifying that the provided API key
|
||||
* is in a valid format, and the route being accessed is allowed
|
||||
* for the given key.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param \Closure $next
|
||||
* @return mixed
|
||||
*
|
||||
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
|
||||
* @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
|
||||
*/
|
||||
public function handle(Request $request, Closure $next)
|
||||
{
|
||||
if (is_null($request->bearerToken())) {
|
||||
throw new HttpException(401, null, null, ['WWW-Authenticate' => 'Bearer']);
|
||||
}
|
||||
|
||||
try {
|
||||
$model = $this->repository->findFirstWhere([['token', '=', $request->bearerToken()]]);
|
||||
} catch (RecordNotFoundException $exception) {
|
||||
throw new AccessDeniedHttpException;
|
||||
}
|
||||
|
||||
$this->auth->guard()->loginUsingId($model->user_id);
|
||||
$request->attributes->set('api_key', $model);
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
58
app/Http/Middleware/API/HasPermissionToResource.php
Normal file
58
app/Http/Middleware/API/HasPermissionToResource.php
Normal file
|
@ -0,0 +1,58 @@
|
|||
<?php
|
||||
|
||||
namespace Pterodactyl\Http\Middleware\API;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Pterodactyl\Contracts\Repository\ApiKeyRepositoryInterface;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
|
||||
|
||||
class HasPermissionToResource
|
||||
{
|
||||
/**
|
||||
* @var \Pterodactyl\Contracts\Repository\ApiKeyRepositoryInterface
|
||||
*/
|
||||
private $repository;
|
||||
|
||||
/**
|
||||
* HasPermissionToResource constructor.
|
||||
*
|
||||
* @param \Pterodactyl\Contracts\Repository\ApiKeyRepositoryInterface $repository
|
||||
*/
|
||||
public function __construct(ApiKeyRepositoryInterface $repository)
|
||||
{
|
||||
$this->repository = $repository;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if an API key has permission to access the given route.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param \Closure $next
|
||||
* @param string $role
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle(Request $request, Closure $next, string $role = 'admin')
|
||||
{
|
||||
/** @var \Pterodactyl\Models\APIKey $model */
|
||||
$model = $request->attributes->get('api_key');
|
||||
|
||||
if ($role === 'admin' && ! $request->user()->root_admin) {
|
||||
throw new NotFoundHttpException;
|
||||
}
|
||||
|
||||
$this->repository->loadPermissions($model);
|
||||
$routeKey = str_replace(['api.', 'admin.'], '', $request->route()->getName());
|
||||
|
||||
$count = $model->getRelation('permissions')->filter(function ($permission) use ($routeKey) {
|
||||
return $routeKey === str_replace('-', '.', $permission->permission);
|
||||
})->count();
|
||||
|
||||
if ($count === 1) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
throw new AccessDeniedHttpException('Cannot access resource without required `' . $routeKey . '` permission.');
|
||||
}
|
||||
}
|
52
app/Http/Middleware/API/SetSessionDriver.php
Normal file
52
app/Http/Middleware/API/SetSessionDriver.php
Normal file
|
@ -0,0 +1,52 @@
|
|||
<?php
|
||||
|
||||
namespace Pterodactyl\Http\Middleware\API;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Barryvdh\Debugbar\LaravelDebugbar;
|
||||
use Illuminate\Contracts\Foundation\Application;
|
||||
use Illuminate\Contracts\Config\Repository as ConfigRepository;
|
||||
|
||||
class SetSessionDriver
|
||||
{
|
||||
/**
|
||||
* @var \Illuminate\Contracts\Foundation\Application
|
||||
*/
|
||||
private $app;
|
||||
|
||||
/**
|
||||
* @var \Illuminate\Contracts\Config\Repository
|
||||
*/
|
||||
private $config;
|
||||
|
||||
/**
|
||||
* SetSessionDriver constructor.
|
||||
*
|
||||
* @param \Illuminate\Contracts\Foundation\Application $app
|
||||
* @param \Illuminate\Contracts\Config\Repository $config
|
||||
*/
|
||||
public function __construct(Application $app, ConfigRepository $config)
|
||||
{
|
||||
$this->app = $app;
|
||||
$this->config = $config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the session for API calls to only last for the one request.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param \Closure $next
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle(Request $request, Closure $next)
|
||||
{
|
||||
if ($this->app->environment() !== 'production') {
|
||||
$this->app->make(LaravelDebugbar::class)->disable();
|
||||
}
|
||||
|
||||
$this->config->set('session.driver', 'array');
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
|
@ -1,209 +0,0 @@
|
|||
<?php
|
||||
/**
|
||||
* Pterodactyl - Panel
|
||||
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
|
||||
*
|
||||
* This software is licensed under the terms of the MIT license.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
namespace Pterodactyl\Http\Middleware;
|
||||
|
||||
use Auth;
|
||||
use Crypt;
|
||||
use Config;
|
||||
use Closure;
|
||||
use Debugbar;
|
||||
use IPTools\IP;
|
||||
use IPTools\Range;
|
||||
use Illuminate\Http\Request;
|
||||
use Pterodactyl\Models\APIKey;
|
||||
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; // 400
|
||||
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; // 403
|
||||
|
||||
class HMACAuthorization
|
||||
{
|
||||
/**
|
||||
* The algorithm to use for handling HMAC encryption.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
const HMAC_ALGORITHM = 'sha256';
|
||||
|
||||
/**
|
||||
* Stored values from the Authorization header.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $token = [];
|
||||
|
||||
/**
|
||||
* The eloquent model for the API key.
|
||||
*
|
||||
* @var \Pterodactyl\Models\APIKey
|
||||
*/
|
||||
protected $key;
|
||||
|
||||
/**
|
||||
* The illuminate request object.
|
||||
*
|
||||
* @var \Illuminate\Http\Request
|
||||
*/
|
||||
private $request;
|
||||
|
||||
/**
|
||||
* Construct class instance.
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
Debugbar::disable();
|
||||
Config::set('session.driver', 'array');
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle an incoming request for the API.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param \Closure $next
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle(Request $request, Closure $next)
|
||||
{
|
||||
$this->request = $request;
|
||||
|
||||
$this->checkBearer();
|
||||
$this->validateRequest();
|
||||
$this->validateIPAccess();
|
||||
$this->validateContents();
|
||||
|
||||
Auth::loginUsingId($this->key()->user_id);
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks that the Bearer token is provided and in a valid format.
|
||||
*
|
||||
*
|
||||
* @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
|
||||
*/
|
||||
protected function checkBearer()
|
||||
{
|
||||
if (empty($this->request()->bearerToken())) {
|
||||
throw new BadRequestHttpException('Request was missing required Authorization header.');
|
||||
}
|
||||
|
||||
$token = explode('.', $this->request()->bearerToken());
|
||||
if (count($token) !== 2) {
|
||||
throw new BadRequestHttpException('The Authorization header passed was not in a validate public/private key format.');
|
||||
}
|
||||
|
||||
$this->token = [
|
||||
'public' => $token[0],
|
||||
'hash' => $token[1],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the request contains a valid public API key
|
||||
* as well as permissions for the resource.
|
||||
*
|
||||
*
|
||||
* @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
|
||||
*/
|
||||
protected function validateRequest()
|
||||
{
|
||||
$this->key = APIKey::where('public', $this->public())->first();
|
||||
if (! $this->key) {
|
||||
throw new AccessDeniedHttpException('Unable to identify requester. Authorization token is invalid.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the requesting IP address is allowed to use this API key.
|
||||
*
|
||||
* @return bool
|
||||
*
|
||||
* @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
|
||||
*/
|
||||
protected function validateIPAccess()
|
||||
{
|
||||
if (! is_null($this->key()->allowed_ips)) {
|
||||
foreach (json_decode($this->key()->allowed_ips) as $ip) {
|
||||
if (Range::parse($ip)->contains(new IP($this->request()->ip()))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
throw new AccessDeniedHttpException('This IP address does not have permission to access the API using these credentials.');
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the HMAC sent in the request matches the one generated
|
||||
* on the panel side.
|
||||
*
|
||||
*
|
||||
* @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
|
||||
*/
|
||||
protected function validateContents()
|
||||
{
|
||||
if (! hash_equals(base64_decode($this->hash()), $this->generateSignature())) {
|
||||
throw new BadRequestHttpException('The HMAC for the request was invalid.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a HMAC from the request and known API secret key.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function generateSignature()
|
||||
{
|
||||
$content = urldecode($this->request()->fullUrl()) . $this->request()->getContent();
|
||||
|
||||
return hash_hmac(self::HMAC_ALGORITHM, $content, Crypt::decrypt($this->key()->secret), true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the public key passed in the Authorization header.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function public()
|
||||
{
|
||||
return $this->token['public'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the base64'd HMAC sent in the Authorization header.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function hash()
|
||||
{
|
||||
return $this->token['hash'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the API Key model.
|
||||
*
|
||||
* @return \Pterodactyl\Models\APIKey
|
||||
*/
|
||||
protected function key()
|
||||
{
|
||||
return $this->key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the Illuminate Request object.
|
||||
*
|
||||
* @return \Illuminate\Http\Request
|
||||
*/
|
||||
private function request()
|
||||
{
|
||||
return $this->request;
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue