Skip to content

ActiveDirectoryPassword and sqlpassword authentication - #661

Closed
Hadis-Fard wants to merge 44 commits into
tediousjs:masterfrom
Hadis-Fard:fedauth
Closed

Hadis-Fard wants to merge 44 commits into
tediousjs:masterfrom
Hadis-Fard:fedauth

Conversation

@Hadis-Fard

@Hadis-Fard Hadis-Fard commented Dec 18, 2017 •

Copy link
Copy Markdown
  • wrote prelogin for fedauth

  • wrote login7 and response for fedauth

  • added adal-node lib to generate token

  • added authentication keyword to config options, the valid values are ActiveDirectoryPassword and SQLPassword (at the moment), where sqlpassword is added for consistency and is only used for secure connection to on-premise server. for AD password authentication, user should be a valid AAD user. You might want to set trustServerCertificate to true if you don't have certificate on client machine.

// ActiveDirectoryPassword authentication method
new Connection({
  "server": "yourADserver.database.windows.net",
  "userName": "yourADuser",
  "password": "yourStrong(!)Password",
  "options": {
    "database": "FederatedAuthDB",
   "authentication": "ActiveDirectoryPassword",
    "trustServerCertificate" : true,
  }
});
// SQLPassword authentication method
new Connection({
  "server": "localhost",
  "userName": "sa",
  "password": "yourStrong(!)Password",
  "options": {
    "database": "yourDB",
    "authentication": "SQLPassword",
    "trustServerCertificate" : true
  }
});
  • TODOs:
    • ActiveDirectoryIntegrated support
    • SecurityToken support

@arthurschreiber

Copy link
Copy Markdown
Collaborator

@Hadis-Fard Thank you for opening this pull request! ❤️ 😍

I'll try to take a look over the next few days and see if I can leave a few comments.

Comment thread src/connection.js
throw new Error(`Azure Active Directory authentication is not supported in the TDS version ${this.config.options.tdsVersion}`);
}
this.config.options.encrypt = true;
this.fedAuthInfo.method = config.options.authentication;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Just an FYI, encrypt will be true by default once #606 is merged.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Isn't better to drop it after the PR is merged? cause without encryption fed auth would fail, so I think it's better to set it to true for now

Comment thread src/connection.js Outdated
}

if (this.config.domain && !this.config.userName && !this.config.password) {
this.config.options.useWindowsIntegratedAuth = true;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Can you remove the reference to WindowsIntegratedAuth 😅

Comment thread src/connection.js
this.config.options.encrypt = true;
this.fedAuthInfo.method = config.options.authentication;
if (config.options.trustServerCertificate != 'true') {
this.config.options.trustServerCertificate = false;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

this.config.options.trustServerCertificate is already has a boolean value (set here), can you remove this validation?

@Hadis-Fard Hadis-Fard Jan 3, 2018 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

it could be set to anything (for example it could be 'abcd') up there, and I wanna make sure unless it is explicitly set to true by user, it is false.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

You're right! For most of the boolean options, error is thrown if value is not boolean (like here), looks like config.options.trustServerCertificate was missed. Can you do the same for trustServerCertificate too? It would be more generic.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Yeah, we should catch this and require it to be a boolean if it is set. As this change is orthogonal to active directory auth, could you do this in a separate pull request?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

@v-suhame @arthurschreiber sent PR #692 for checking the boolean config types

Comment thread src/connection.js Outdated

if (0 != preloginPayload.fedAuthRequired && 1 != preloginPayload.fedAuthRequired) {
this.emit('connect', ConnectionError('Server sent an unexpected value for FedAuthRequired PreLogin Option. Value was' + preloginPayload.fedAuthRequired, 'EFEDAUTH'));
return this.close();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This error would be triggered for all older versions of SQL Server that doesn't support fedAuth 🤔 How about changing the condition such that error is triggered only when client requests fedAuth and server responds with something other than 1 or 0?

Comment thread src/connection.js Outdated
return this.close();
}
// fedAuthRequired is used for capability negotiation when choosing between SSPI and federated authentication
if (preloginPayload.fedAuthRequired === 1 && this.config.domain) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

What do you think about adding TODO/Note here so that we remember to extend this condition to include other SSPI auths (Windows integrated and Kerberos) in future.

Comment thread src/connection.js Outdated

if (this.fedAuthInfo.method != undefined) {
if (0 != preloginPayload.fedAuthRequired && 1 != preloginPayload.fedAuthRequired) {
this.emit('connect', ConnectionError('Server sent an unexpected value for FedAuthRequired PreLogin Option. Value was' + preloginPayload.fedAuthRequired, 'EFEDAUTH'));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Can you use template strings for error message? It will be easier to keep track of spaces while appending variables.
Also, I think this message is too technical for users to understand 😅 FedAuthRequired PreLogin Option

Comment thread src/token/feature-ext-parser.js Outdated
module.exports.fedAuthInfoParser = fedAuthInfoParser;
function fedAuthInfoParser(parser, colMetadata, options, callback) {
parser.readUInt32LE((tokenLength) => {
parser.readUInt32LE((countOfInfoIDs) => {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nesting many parser.readXYZ calls is really expensive and slow, due to callback nesting involved. 😞

Could we change this to instead just read tokenLength via parser.readUInt32LE, and then read the whole token into a Buffer in one go via parser.readBuffer(tokenLength, (data) => { ... }). All other data extraction could then happen using regular Buffer operations, without any callbacks being involved.

@Hadis-Fard What do you think? 😄

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

good idea, I play with it to see what i can do

Comment thread src/token/feature-ext-parser.js Outdated
}

module.exports.featureExtAckParser = featureExtAckParser;
function featureExtAckParser(parser, colMetadata, options, callback) {

@arthurschreiber arthurschreiber Jan 23, 2018 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@Hadis-Fard What do you think about breaking this up into two separate files, one for parsing FEDAUTHINFO and the other for FEATUREEXTACK?

Comment thread src/login7-payload.js Outdated
return buffer.data;
}

CreateFedAuthExtData(buffer, fedAuthInfo) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

What do you think about changing this to createFedAuthExtData to match the method naming convention?

Comment thread src/prelogin-payload.js Outdated

toString(indent) {
indent || (indent = '');
return indent + 'PreLogin - ' + sprintf('version:%d.%d.%d.%d %d, encryption:0x%02X(%s), instopt:0x%02X, threadId:0x%08X, mars:0x%02X(%s)', this.version.major, this.version.minor, this.version.patch, this.version.trivial, this.version.subbuild, this.encryption ? this.encryption : 0, this.encryptionString ? this.encryptionString : 0, this.instance ? this.instance : 0, this.threadId ? this.threadId : 0, this.mars ? this.mars : 0, this.marsString ? this.marsString : 0);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Can you add fedAuthRequired to the debug payload data here?

@Hadis-Fard

Copy link
Copy Markdown
Author

@v-suhame @arthurschreiber Hey guys, I fixed the issues you caught, would you please review the changes I made?

  • Added separate file for fedauth info parser
  • flattened the nested callbacks by reading buffer at once and parsing it using buffer operator.
  • Added fedAuthRequired to the debug payload data.
  • Fixed the error messages
  • Used push operator to add createfedAuth () to array

Comment thread src/connection.js Outdated
if (this.fedAuthInfo.method != undefined) {
if (0 != preloginPayload.fedAuthRequired && 1 != preloginPayload.fedAuthRequired) {
this.emit('connect', ConnectionError(`Server sent an unexpected response for federated authentication value during negotiation. Value was ${preloginPayload.fedAuthRequired}`, 'EFEDAUTH'));
return this.close();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Can you fix the double space in error message? Value was __ ${preloginPayload.fedAuthRequired} 😜

Comment thread src/login7-payload.js Outdated
variableData.offsetsAndLengths.writeUInt16LE(variableData.offset);
variableData.offsetsAndLengths.writeUInt16LE(4);
//placeHolder
this.tempHolder = variableData.data.getPos();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Can you change tempHolder into a more meaningful variable name? Like tempHolder of what?

@Hadis-Fard Hadis-Fard Jan 31, 2018 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Now that i look at this again, i guess it can be better designed, it doesn't make sense that addVariableDataInt writes the placeholder in function, it is tailored to fit only fedauth(or ibExtension), and it cannot be used for any other purposes

Comment thread src/connection.js
});

this.tokenStreamParser.on('fedAuthInfo', (token) => {
const clientId = '7f98cb04-cd1e-40df-9140-3bf7e2cea4db';

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

What is the meaning behind this value? 😅

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

With this id Azure Active Direcotry would know what's getting connected to it, it's registered within Azure. :)

Comment thread src/connection.js
const payload = new PreloginPayload({
encrypt: this.config.options.encrypt
encrypt: this.config.options.encrypt,
fedAuthRequested: (this.fedAuthInfo.method != undefined)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Can/should method be null here? Maybe we should just restrict this to just checking for undefined?

Comment thread src/connection.js
return preloginPayload.toString(' ');
});

if (this.fedAuthInfo.method != undefined) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Same as above. If we can limit the potential types of method, that'd be ✨

Comment thread src/connection.js Outdated
});

if (this.fedAuthInfo.method != undefined) {
if (0 != preloginPayload.fedAuthRequired && 1 != preloginPayload.fedAuthRequired) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Maybe we should refactor this to be moved out of the connection code and into the prelogin payload parser? I think that's where this would belong to, conceptually. 😅

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

🤔 if we move it to preloginpayload, we won't have access to the connection class, and can't access Connection error or close. the processPreLoginResponse gets the feauth prelogin response and processes it similar to encryptionString

Comment thread src/connection.js Outdated
return this.close();
}
// fedAuthRequired is used for capability negotiation when choosing between SSPI and federated authentication
if (preloginPayload.fedAuthRequired === 1 && this.config.domain) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I think the TDS specification states that both SSPI and FedAuth can be used at the same time, and the remote SQL Server will then use whatever connection mechanism it deems to be more appropriate.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

right on 👌 thanks for catching this

Comment thread src/connection.js Outdated

sendFedAuthResponsePacket() {
const accessTokenLen = Buffer.byteLength(this.fedAuthInfo.token.accessToken, 'ucs2');
const data = new WritableTrackingBuffer(4 + accessTokenLen);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

What do you think about using a regular Buffer instead of a WritableTrackingBuffer here? The length of the data is fixed, so WritableTrackingBuffer just adds bookkeeping overhead without providing any real advantages.

Comment thread src/connection.js Outdated

const boundTransitionTo = this.transitionTo.bind(this);
// sent the fedAuth token message, the rest is similar to standard login 7
process.nextTick(boundTransitionTo, this.STATE.SENT_LOGIN7_WITH_STANDARD_LOGIN);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

What do you think about using an arrow function here, instead of using Function.prototype.bind?

process.nextTick(() => {
  this.transitionTo(this.STATE.SENT_LOGIN7_WITH_STANDARD_LOGIN);
});

Comment thread src/token/fedauth-info-parser.js Outdated
@@ -0,0 +1,62 @@
const async = require('async');

var readFedAuthInfoOpt = (data, infoData, callback) => {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

What do you think about just changing this to a regular function definition?

function readFedAuthInfoOpt(data, infoData, callback) {
  ...
}

Arrow functions are usually only preferred when we want to have a function bound to the surrounding this scope, or we want a shorter way of defining a closure, neither of which applies here. 😅

Comment thread src/token/fedauth-info-parser.js Outdated
const async = require('async');

var readFedAuthInfoOpt = (data, infoData, callback) => {
const FEDAUTHINFOID = {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

What do you think about pulling this constant to the top level scope, to ensure it does not get re-defined on each function call?

Comment thread src/token/fedauth-info-parser.js Outdated
}

if (infoData.spnLen && infoData.stsurlLen) {
const spn = data.slice(infoData.spnOffset, infoData.spnOffset + infoData.spnLen);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Instead of slicing out a new Buffer, and then converting the Buffer to a string via Buffer.prototype.toString, I think we could use Buffer.prototype.toString directly. Also, I think by specifying the correct encoding (ucs2), we could get rid of the String.prototype.replace call to filter out the null bytes:

const spn = data.toString('ucs2', infoData.spnOffset, infoData.spnOffset + infoData.spnLen);
const stsurl = data.toString('ucs2', infoData.stsurlOffset, infoData.stsurlOffset + infoData.stsurlLen);

@Hadis-Fard

Hadis-Fard commented Feb 8, 2018 •

Copy link
Copy Markdown
Author

❤️ the detailed reviews! so here is the summary of the updates:

  • removed extra spaces
  • used buffer instead of writable tracking buffer
  • pushed the constants to the outer scope
  • used arrow function instead of bind(this) for state transitioning
  • restricted fedauth method to udefined
  • removed the error to let the server decide on authentication mechanism

@Hadis-Fard

Copy link
Copy Markdown
Author

commitlint is not happy about all previous commit messages here, opened #707

@Hadis-Fard Hadis-Fard closed this Feb 8, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants