Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
44 commits
Select commit Hold shift + click to select a range
2d43f36
Fedauth- added prelogin, and adal dependecy
Nov 7, 2017
b2d0a5c
resolved merge conflicts
Nov 7, 2017
3f1840d
added fedauth flags to login7, writeFedauth feature ext
Nov 15, 2017
3d3b3d7
Merge branch 'master' of https://github.com/tediousjs/tedious
Nov 15, 2017
4cf47ed
added create feature ext, and fedauth ext packet
Nov 16, 2017
e7f385b
added fExtesnion in flag3
Nov 28, 2017
46d2d58
added fedauth info parser, and fedauth info event
Nov 28, 2017
4f6f7a1
added fedauth token
Nov 28, 2017
936713a
added adal-node lib
Dec 12, 2017
7eac627
fixed ibextension offset in login7
Dec 12, 2017
7ca7afc
generate token, send token, and recieve response
Dec 12, 2017
f977a46
merge conflicts
Dec 12, 2017
c12d559
initial feature ext ack parser and connection
Dec 12, 2017
c6b1914
recursive implementation of feature ext parser
Dec 13, 2017
fce3230
clean up feature ext parser and added error for auth and sspi
Dec 14, 2017
eb804f4
added errors and code clean up
Dec 15, 2017
d05e2ff
validate fedauth is only used with tds 7_4
Dec 18, 2017
d668c1e
error on tds version and fedauth and clean up
Dec 18, 2017
7d9eab4
deleted debugging logs, fixed login 7 payload
Dec 18, 2017
f679c92
annotated writeAtPosition with flow types
Dec 18, 2017
514666b
used sent standard login 7 state
Dec 19, 2017
fb8b03e
added error for security token, and fixed review comments
Jan 4, 2018
bbaf393
fixed linter issue
Jan 4, 2018
ddc9299
restriced fedauth prelogin flag to when user has requested it
Jan 5, 2018
559349a
prelogin unit test
Jan 5, 2018
e058282
fixed merge conflicts
Jan 8, 2018
b928f0f
fixed linter issues
Jan 8, 2018
9a8e3f2
Merge branch 'master' of https://github.com/tediousjs/tedious into fe…
Jan 11, 2018
e2d695c
chore: Merge branch 'master' of https://github.com/tediousjs/tedious …
Jan 23, 2018
2c7388a
refactor: fix peer reiview comments
Jan 26, 2018
2187468
refactor: add separate file for fedauth parser, flatten the nested ca…
Jan 26, 2018
287d27a
chore: remove global var, newline
Jan 26, 2018
b4b9310
Merge branch 'master' of https://github.com/tediousjs/tedious into fe…
Jan 26, 2018
a74cc22
chore: fix indentation
Jan 26, 2018
a26b779
chore: fix merge conflicts
Feb 7, 2018
b2d2ac3
refactor: use buffer, state transition in callback
Feb 7, 2018
303650a
refactor: update the way fedauthrequired response is handled
Feb 8, 2018
3ed5425
refactor: change passing login7 featureext position
Feb 8, 2018
a2766f5
feat: IDN support
Feb 2, 2018
c2700a7
test: add unit test for IDN Server names
Feb 6, 2018
225dedb
test: add tests for unicode server with instance name
Feb 6, 2018
cab06d1
chore: merge upstream package.json
Feb 8, 2018
4913dc4
chore: removed extranous space
Feb 8, 2018
30c3590
chore: merge branch 'master'
Feb 8, 2018
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
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,14 @@
"tag": "next"
},
"dependencies": {
"adal-node": "^0.1.22",
"babel-runtime": "^6.26.0",
"big-number": "0.3.1",
"bl": "^1.2.0",
"commitlint": "^6.1.0",
"depd": "^1.1.2",
"iconv-lite": "^0.4.11",
"punycode": "^2.1.0",
"readable-stream": "^2.2.6",
"sprintf-js": "^1.1.1",
"punycode": "^2.1.0"
Expand Down
148 changes: 140 additions & 8 deletions src/connection.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
const deprecate = require('depd')('tedious');

const BulkLoad = require('./bulk-load');
const Debug = require('./debug');
const EventEmitter = require('events').EventEmitter;
Expand All @@ -20,6 +19,7 @@ const crypto = require('crypto');
const ConnectionError = require('./errors').ConnectionError;
const RequestError = require('./errors').RequestError;
const Connector = require('./connector').Connector;
const AuthenticationContext = require('adal-node').AuthenticationContext;

// A rather basic state machine for managing a connection.
// Implements something approximating s3.2.1.
Expand Down Expand Up @@ -79,6 +79,19 @@ class Connection extends EventEmitter {
throw new TypeError('Invalid server: ' + config.server);
}

this.fedAuthInfo = {
ValidFedAuthEnum: {
SqlPassword: 'SQLPASSWORD',
ActiveDirectoryPassword: 'ACTIVEDIRECTORYPASSWORD',
// TODO: ActiveDirectoryIntegrated
},
method: undefined,
fedAuthLibrary: undefined,
requiredPreLoginResponse: false,
fedAuthInfoRequested: false,
responsePending: false,
token: undefined
};
if (config.domain != undefined) {
deprecateNonStringConfigValue('domain', config.domain);
}
Expand Down Expand Up @@ -145,6 +158,7 @@ class Connection extends EventEmitter {
tdsVersion: DEFAULT_TDS_VERSION,
textsize: DEFAULT_TEXTSIZE,
trustServerCertificate: true,
authentication: undefined,
useColumnNames: false,
useUTC: true
}
Expand Down Expand Up @@ -479,6 +493,25 @@ class Connection extends EventEmitter {
deprecateNonBooleanConfigValue('options.useUTC', config.options.useUTC);
this.config.options.useUTC = config.options.useUTC;
}

// Whenever authentication property is used to specify an authentication method,
// the client will request encryption (the default value of the Encrypt property will be true)
// and it will validate the server certificate (regardless of the encryption setting), unless TrustServerCertificate = true
if (config.options.authentication != undefined) {
// check for valid options
if (!(config.options.authentication.toUpperCase() === this.fedAuthInfo.ValidFedAuthEnum.SqlPassword ||
config.options.authentication.toUpperCase() === this.fedAuthInfo.ValidFedAuthEnum.ActiveDirectoryPassword)) {
throw new Error('An invalid authentication method is specified');
}
if (this.config.options.tdsVersion < '7_4') {
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

if (!config.options.trustServerCertificate) {
this.config.options.trustServerCertificate = false;
}
}
deprecateNullConfigValue('options.useUTC', config.options.useUTC);
}

Expand All @@ -496,6 +529,7 @@ class Connection extends EventEmitter {
this.transactionDescriptors = [new Buffer([0, 0, 0, 0, 0, 0, 0, 0])];
this.transitionTo(this.STATE.CONNECTING);


if (this.config.options.tdsVersion < '7_2') {
// 'beginTransaction', 'commitTransaction' and 'rollbackTransaction'
// events are utilized to maintain inTransaction property state which in
Expand Down Expand Up @@ -605,6 +639,23 @@ class Connection extends EventEmitter {
this.emit('charsetChange', token.newValue);
});

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. :)

if (token.fedAuthInfoData.stsurl && token.fedAuthInfoData.spn) {
this.fedAuthInfo.responsePending = true;
var context = new AuthenticationContext(token.fedAuthInfoData.stsurl);
context.acquireTokenWithUsernamePassword(token.fedAuthInfoData.spn, this.config.userName, this.config.password, clientId, (err, tokenResponse) => {
if (err) {
this.fedAuthInfo.responsePending = false;
this.loginError = ConnectionError('Security token could not be authenticated or authorized.', 'EFEDAUTH');
} else {
this.fedAuthInfo.responsePending = false;
this.fedAuthInfo.token = tokenResponse;
}
});
}
});

this.tokenStreamParser.on('loginack', (token) => {
if (!token.tdsVersion) {
// unsupported TDS version
Expand Down Expand Up @@ -971,7 +1022,8 @@ class Connection extends EventEmitter {

sendPreLogin() {
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?

});
this.messageIo.sendMessage(TYPE.PRELOGIN, payload.data);
this.debug.payload(function() {
Expand All @@ -992,7 +1044,13 @@ class Connection extends EventEmitter {
this.debug.payload(function() {
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 ✨

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();
}
this.fedAuthInfo.requiredPreLoginResponse = (preloginPayload.fedAuthRequired == 1);
}
if (preloginPayload.encryptionString === 'ON' || preloginPayload.encryptionString === 'REQ') {
if (!this.config.options.encrypt) {
this.emit('connect', ConnectionError("Server requires encryption, set 'encrypt' config option to true.", 'EENCRYPT'));
Expand All @@ -1019,7 +1077,8 @@ class Connection extends EventEmitter {
initDbFatal: !this.config.options.fallbackToDefaultDb,
readOnlyIntent: this.config.options.readOnlyIntent,
sspiBlob: clientResponse,
language: this.config.options.language
language: this.config.options.language,
fedAuthInfo: this.fedAuthInfo
});

this.routingData = undefined;
Expand Down Expand Up @@ -1056,6 +1115,22 @@ class Connection extends EventEmitter {
process.nextTick(boundTransitionTo, this.STATE.SENT_NTLM_RESPONSE);
}

sendFedAuthResponsePacket() {
const accessTokenLen = Buffer.byteLength(this.fedAuthInfo.token.accessToken, 'ucs2');
const data = new Buffer(8 + accessTokenLen);
let offset = 0;
data.writeUInt32LE(accessTokenLen + 4, offset);
offset += 4;
data.writeUInt32LE(accessTokenLen, offset);
offset += 4;
data.write(this.fedAuthInfo.token.accessToken, offset, 'ucs2');
this.messageIo.sendMessage(TYPE.FEDAUTH_TOKEN, data);
// sent the fedAuth token message, the rest is similar to standard login 7
process.nextTick(() => {
this.transitionTo(this.STATE.SENT_LOGIN7_WITH_STANDARD_LOGIN);
});
}

// Returns false to apply backpressure.
sendDataToTokenStreamParser(data) {
return this.tokenStreamParser.addBuffer(data);
Expand Down Expand Up @@ -1214,6 +1289,19 @@ class Connection extends EventEmitter {
}
}

processLogin7FedAuthResponse() {
if (this.fedAuthInfo.fedAuthInfoRequested && !this.loginError) {
return this.dispatchEvent('receivedFedAuthInfo');
} else {
if (this.loginError) {
this.emit('connect', this.loginError);
} else {
this.emit('connect', ConnectionError('Login failed.', 'ELOGIN'));
}
return this.dispatchEvent('loginFailed');
}
}

execSqlBatch(request) {
this.makeRequest(request, TYPE.SQL_BATCH, new SqlBatchPayload(request.sqlTextOrProcedure, this.currentTransactionDescriptor(), this.config.options));
}
Expand Down Expand Up @@ -1619,10 +1707,13 @@ Connection.prototype.STATE = {
message: function() {
if (this.messageIo.tlsNegotiationComplete) {
this.sendLogin7Packet(() => {
if (this.config.domain) {
this.transitionTo(this.STATE.SENT_LOGIN7_WITH_NTLM);
} else {
this.transitionTo(this.STATE.SENT_LOGIN7_WITH_STANDARD_LOGIN);
if (this.fedAuthInfo.requiredPreLoginResponse) {
return this.transitionTo(this.STATE.SENT_LOGIN7_WITH_FEDAUTH);
} else if (this.config.domain) {
return this.transitionTo(this.STATE.SENT_LOGIN7_WITH_NTLM);
}
else {
return this.transitionTo(this.STATE.SENT_LOGIN7_WITH_STANDARD_LOGIN);
}
});
}
Expand Down Expand Up @@ -1704,6 +1795,47 @@ Connection.prototype.STATE = {
}
}
},
SENT_LOGIN7_WITH_FEDAUTH: {
name: 'SentLogin7Withfedauth',
events: {
socketError: function() {
return this.transitionTo(this.STATE.FINAL);
},
connectTimeout: function() {
return this.transitionTo(this.STATE.FINAL);
},
data: function(data) {
if (this.fedAuthInfo.responsePending) {
// We got data from the server while we're waiting for adal authentication context
// call to complete on the client. We cannot process server data
// until this call completes as the state can change on completion of
// the call. Queue it for later.
const boundDispatchEvent = this.dispatchEvent.bind(this);
return setImmediate(boundDispatchEvent, 'data', data);
} else {
return this.sendDataToTokenStreamParser(data);
}
},
receivedFedAuthInfo: function() {
return this.sendFedAuthResponsePacket();
},
loginFailed: function() {
return this.transitionTo(this.STATE.FINAL);
},
message: function() {
if (this.fedAuthInfo.responsePending) {
// We got data from the server while we're waiting for adal authentication context
// call to complete on the client. We cannot process server data
// until this call completes as the state can change on completion of
// the call. Queue it for later.
const boundDispatchEvent = this.dispatchEvent.bind(this);
return setImmediate(boundDispatchEvent, 'message');
} else {
return this.processLogin7FedAuthResponse();
}
}
}
},
LOGGED_IN_SENDING_INITIAL_SQL: {
name: 'LoggedInSendingInitialSql',
enter: function() {
Expand Down
Loading