Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import { getClient } from '../../../../../server/lib/get_client_shield';
import { AuthScopeService } from '../auth_scope_service';
import { BasicAuthenticationProvider } from './providers/basic';
import { TokenAuthenticationProvider } from './providers/token';
import { SAMLAuthenticationProvider } from './providers/saml';
import { AuthenticationResult } from './authentication_result';
import { DeauthenticationResult } from './deauthentication_result';
Expand All @@ -16,6 +17,7 @@ import { Session } from './session';
// provider class that can handle specific authentication mechanism.
const providerMap = new Map([
['basic', BasicAuthenticationProvider],
['token', TokenAuthenticationProvider],
['saml', SAMLAuthenticationProvider]
]);

Expand Down Expand Up @@ -169,6 +171,10 @@ class Authenticator {
}
}

if (authenticationResult.failed()) {
return authenticationResult;
}

if (authenticationResult.succeeded()) {
// we have to do this here, as the auth scope's could be dependent on this
await this._authorizationMode.initialize(request);
Expand Down
119 changes: 78 additions & 41 deletions x-pack/plugins/security/server/lib/authentication/providers/basic.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,41 @@
* you may not use this file except in compliance with the Elastic License.
*/

import Boom from 'boom';
import { canRedirectRequest } from '../../can_redirect_request';
import { AuthenticationResult } from '../authentication_result';
import { DeauthenticationResult } from '../deauthentication_result';

/**
* Utility class that knows how to decorate request with proper Basic authentication headers.
*/
export class BasicCredentials {
Copy link
Contributor Author

@epixa epixa Nov 20, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Super annoying, but the linter has a rule that disallows accessing static methods on BasicCredentials before it is defined in the same file. Even though it's all static. Dumb.

Anyway, I copied and pasted BasicCredentials without changes to the top of the file so linting would stop failing

/**
* Takes provided `username` and `password`, transforms them into proper `Basic ***` authorization
* header and decorates passed request with it.
* @param {Hapi.Request} request HapiJS request instance.
* @param {string} username User name.
* @param {string} password User password.
* @returns {Hapi.Request} HapiJS request instance decorated with the proper header.
*/
static decorateRequest(request, username, password) {
if (!request || typeof request !== 'object') {
throw new Error('Request should be a valid object.');
}

if (!username || typeof username !== 'string') {
throw new Error('Username should be a valid non-empty string.');
}

if (!password || typeof password !== 'string') {
throw new Error('Password should be a valid non-empty string.');
}

const basicCredentials = new Buffer(`${username}:${password}`).toString('base64');
request.headers.authorization = `Basic ${basicCredentials}`;
return request;
}
}

/**
* Object that represents available provider options.
* @typedef {{
Expand Down Expand Up @@ -49,8 +79,15 @@ export class BasicAuthenticationProvider {
async authenticate(request, state) {
this._options.log(['debug', 'security', 'basic'], `Trying to authenticate user request to ${request.url.path}.`);

let authenticationResult = await this._authenticateViaHeader(request);
// first try from login payload
let authenticationResult = await this._authenticateViaLoginAttempt(request);

// if there isn't a payload, try header-based token auth
if (authenticationResult.notHandled()) {
authenticationResult = await this._authenticateViaHeader(request);
}

// if we still can't attempt auth, try authenticating via state (session token)
if (authenticationResult.notHandled() && state) {
authenticationResult = await this._authenticateViaState(request, state);
} else if (authenticationResult.notHandled() && canRedirectRequest(request)) {
Expand Down Expand Up @@ -96,27 +133,58 @@ export class BasicAuthenticationProvider {
const authenticationSchema = authorization.split(/\s+/)[0];
if (authenticationSchema.toLowerCase() !== 'basic') {
this._options.log(['debug', 'security', 'basic'], `Unsupported authentication schema: ${authenticationSchema}`);

// It's essential that we fail if non-empty, but unsupported authentication schema
// is provided to allow authenticator to consult other authentication providers
// that may support that schema.
return AuthenticationResult.failed(
Boom.badRequest(`Unsupported authentication schema: ${authenticationSchema}`)
);
return AuthenticationResult.notHandled();
}

try {
const user = await this._options.client.callWithRequest(request, 'shield.authenticate');

this._options.log(['debug', 'security', 'basic'], 'Request has been authenticated via header.');

return AuthenticationResult.succeeded(user, { authorization });
return AuthenticationResult.succeeded(user);
} catch(err) {
this._options.log(['debug', 'security', 'basic'], `Failed to authenticate request via header: ${err.message}`);
return AuthenticationResult.failed(err);
}
}

/**
* @param {Hapi.Request} request HapiJS request instance.
* @returns {Promise.<AuthenticationResult>}
* @private
*/
async _authenticateViaLoginAttempt(request) {
this._options.log(['debug', 'security', 'basic'], 'Trying to authenticate via login attempt.');

const credentials = request.loginAttempt(request).getCredentials();
if (!credentials) {
this._options.log(['debug', 'security', 'basic'], 'Username and password not found in payload.');
return AuthenticationResult.notHandled();
}

try {
const { username, password } = credentials;

BasicCredentials.decorateRequest(request, username, password);
const user = await this._options.client.callWithRequest(request, 'shield.authenticate');

this._options.log(['debug', 'security', 'basic'], 'Request has been authenticated via login attempt.');

return AuthenticationResult.succeeded(user, { authorization: request.headers.authorization });
} catch(err) {
this._options.log(['debug', 'security', 'basic'], `Failed to authenticate request via login attempt: ${err.message}`);

// Reset `Authorization` header we've just set. We know for sure that it hasn't been defined before,
// otherwise it would have been used or completely rejected by the `authenticateViaHeader`.
// We can't just set `authorization` to `undefined` or `null`, we should remove this property
// entirely, otherwise `authorization` header without value will cause `callWithRequest` to fail if
// it's called with this request once again down the line (e.g. in the next authentication provider).
delete request.headers.authorization;

return AuthenticationResult.failed(err);
}
}

/**
* Tries to extract authorization header from the state and adds it to the request before
* it's forwarded to Elasticsearch backend.
Expand Down Expand Up @@ -155,34 +223,3 @@ export class BasicAuthenticationProvider {
}
}
}

/**
* Utility class that knows how to decorate request with proper Basic authentication headers.
*/
export class BasicCredentials {
/**
* Takes provided `username` and `password`, transforms them into proper `Basic ***` authorization
* header and decorates passed request with it.
* @param {Hapi.Request} request HapiJS request instance.
* @param {string} username User name.
* @param {string} password User password.
* @returns {Hapi.Request} HapiJS request instance decorated with the proper header.
*/
static decorateRequest(request, username, password) {
if (!request || typeof request !== 'object') {
throw new Error('Request should be a valid object.');
}

if (!username || typeof username !== 'string') {
throw new Error('Username should be a valid non-empty string.');
}

if (!password || typeof password !== 'string') {
throw new Error('Password should be a valid non-empty string.');
}

const basicCredentials = new Buffer(`${username}:${password}`).toString('base64');
request.headers.authorization = `Basic ${basicCredentials}`;
return request;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ function isAccessTokenExpiredError(err) {
}

/**
* Checks the error returned by Elasticsearch as the result of `samlRefreshAccessToken` call and returns `true` if
* Checks the error returned by Elasticsearch as the result of `getAccessToken` call and returns `true` if
* request has been rejected because of invalid refresh token (expired after 24 hours or have been used already),
* otherwise returns `false`.
* @param {Object} err Error returned from Elasticsearch.
Expand Down Expand Up @@ -114,12 +114,7 @@ export class SAMLAuthenticationProvider {
if (authenticationSchema.toLowerCase() !== 'bearer') {
this._options.log(['debug', 'security', 'saml'], `Unsupported authentication schema: ${authenticationSchema}`);

// It's essential that we fail if non-empty, but unsupported authentication schema
// is provided to allow authenticator to consult other authentication providers
// that may support that schema.
return AuthenticationResult.failed(
Boom.badRequest(`Unsupported authentication schema: ${authenticationSchema}`)
);
return AuthenticationResult.notHandled();
}

try {
Expand Down Expand Up @@ -269,7 +264,7 @@ export class SAMLAuthenticationProvider {
access_token: newAccessToken,
refresh_token: newRefreshToken
} = await this._options.client.callWithInternalUser(
'shield.samlRefreshAccessToken',
'shield.getAccessToken',
{ body: { grant_type: 'refresh_token', refresh_token: refreshToken } }
);

Expand Down
Loading