client_handshake.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. // This file was modified by Oracle on June 17, 2021.
  2. // Handshake errors are now maked as fatal and the corresponding events are
  3. // emitted in the command instance itself.
  4. // Modifications copyright (c) 2021, Oracle and/or its affiliates.
  5. // This file was modified by Oracle on September 21, 2021.
  6. // Handshake workflow now supports additional authentication factors requested
  7. // by the server.
  8. // Modifications copyright (c) 2021, Oracle and/or its affiliates.
  9. 'use strict';
  10. const Command = require('./command.js');
  11. const Packets = require('../packets/index.js');
  12. const ClientConstants = require('../constants/client.js');
  13. const CharsetToEncoding = require('../constants/charset_encodings.js');
  14. const auth41 = require('../auth_41.js');
  15. function flagNames(flags) {
  16. const res = [];
  17. for (const c in ClientConstants) {
  18. if (flags & ClientConstants[c]) {
  19. res.push(c.replace(/_/g, ' ').toLowerCase());
  20. }
  21. }
  22. return res;
  23. }
  24. class ClientHandshake extends Command {
  25. constructor(clientFlags) {
  26. super();
  27. this.handshake = null;
  28. this.clientFlags = clientFlags;
  29. this.authenticationFactor = 0;
  30. }
  31. start() {
  32. return ClientHandshake.prototype.handshakeInit;
  33. }
  34. sendSSLRequest(connection) {
  35. const sslRequest = new Packets.SSLRequest(
  36. this.clientFlags,
  37. connection.config.charsetNumber
  38. );
  39. connection.writePacket(sslRequest.toPacket());
  40. }
  41. sendCredentials(connection) {
  42. if (connection.config.debug) {
  43. console.log(
  44. 'Sending handshake packet: flags:%d=(%s)',
  45. this.clientFlags,
  46. flagNames(this.clientFlags).join(', ')
  47. );
  48. }
  49. this.user = connection.config.user;
  50. this.password = connection.config.password;
  51. // "password1" is an alias to the original "password" value
  52. // to make it easier to integrate multi-factor authentication
  53. this.password1 = connection.config.password;
  54. // "password2" and "password3" are the 2nd and 3rd factor authentication
  55. // passwords, which can be undefined depending on the authentication
  56. // plugin being used
  57. this.password2 = connection.config.password2;
  58. this.password3 = connection.config.password3;
  59. this.passwordSha1 = connection.config.passwordSha1;
  60. this.database = connection.config.database;
  61. this.authPluginName = this.handshake.authPluginName;
  62. const handshakeResponse = new Packets.HandshakeResponse({
  63. flags: this.clientFlags,
  64. user: this.user,
  65. database: this.database,
  66. password: this.password,
  67. passwordSha1: this.passwordSha1,
  68. charsetNumber: connection.config.charsetNumber,
  69. authPluginData1: this.handshake.authPluginData1,
  70. authPluginData2: this.handshake.authPluginData2,
  71. compress: connection.config.compress,
  72. connectAttributes: connection.config.connectAttributes,
  73. });
  74. connection.writePacket(handshakeResponse.toPacket());
  75. }
  76. calculateNativePasswordAuthToken(authPluginData) {
  77. // TODO: dont split into authPluginData1 and authPluginData2, instead join when 1 & 2 received
  78. const authPluginData1 = authPluginData.slice(0, 8);
  79. const authPluginData2 = authPluginData.slice(8, 20);
  80. let authToken;
  81. if (this.passwordSha1) {
  82. authToken = auth41.calculateTokenFromPasswordSha(
  83. this.passwordSha1,
  84. authPluginData1,
  85. authPluginData2
  86. );
  87. } else {
  88. authToken = auth41.calculateToken(
  89. this.password,
  90. authPluginData1,
  91. authPluginData2
  92. );
  93. }
  94. return authToken;
  95. }
  96. handshakeInit(helloPacket, connection) {
  97. this.on('error', (e) => {
  98. connection._fatalError = e;
  99. connection._protocolError = e;
  100. });
  101. this.handshake = Packets.Handshake.fromPacket(helloPacket);
  102. if (connection.config.debug) {
  103. console.log(
  104. 'Server hello packet: capability flags:%d=(%s)',
  105. this.handshake.capabilityFlags,
  106. flagNames(this.handshake.capabilityFlags).join(', ')
  107. );
  108. }
  109. connection.serverCapabilityFlags = this.handshake.capabilityFlags;
  110. connection.serverEncoding = CharsetToEncoding[this.handshake.characterSet];
  111. connection.connectionId = this.handshake.connectionId;
  112. const serverSSLSupport =
  113. this.handshake.capabilityFlags & ClientConstants.SSL;
  114. // multi factor authentication is enabled with the
  115. // "MULTI_FACTOR_AUTHENTICATION" capability and should only be used if it
  116. // is supported by the server
  117. const multiFactorAuthentication =
  118. this.handshake.capabilityFlags &
  119. ClientConstants.MULTI_FACTOR_AUTHENTICATION;
  120. this.clientFlags = this.clientFlags | multiFactorAuthentication;
  121. // use compression only if requested by client and supported by server
  122. connection.config.compress =
  123. connection.config.compress &&
  124. this.handshake.capabilityFlags & ClientConstants.COMPRESS;
  125. this.clientFlags = this.clientFlags | connection.config.compress;
  126. if (connection.config.ssl) {
  127. // client requires SSL but server does not support it
  128. if (!serverSSLSupport) {
  129. const err = new Error('Server does not support secure connection');
  130. err.code = 'HANDSHAKE_NO_SSL_SUPPORT';
  131. err.fatal = true;
  132. this.emit('error', err);
  133. return false;
  134. }
  135. // send ssl upgrade request and immediately upgrade connection to secure
  136. this.clientFlags |= ClientConstants.SSL;
  137. this.sendSSLRequest(connection);
  138. connection.startTLS((err) => {
  139. // after connection is secure
  140. if (err) {
  141. // SSL negotiation error are fatal
  142. err.code = 'HANDSHAKE_SSL_ERROR';
  143. err.fatal = true;
  144. this.emit('error', err);
  145. return;
  146. }
  147. // rest of communication is encrypted
  148. this.sendCredentials(connection);
  149. });
  150. } else {
  151. this.sendCredentials(connection);
  152. }
  153. if (multiFactorAuthentication) {
  154. // if the server supports multi-factor authentication, we enable it in
  155. // the client
  156. this.authenticationFactor = 1;
  157. }
  158. return ClientHandshake.prototype.handshakeResult;
  159. }
  160. handshakeResult(packet, connection) {
  161. const marker = packet.peekByte();
  162. // packet can be OK_Packet, ERR_Packet, AuthSwitchRequest, AuthNextFactor
  163. // or AuthMoreData
  164. if (marker === 0xfe || marker === 1 || marker === 0x02) {
  165. const authSwitch = require('./auth_switch');
  166. try {
  167. if (marker === 1) {
  168. authSwitch.authSwitchRequestMoreData(packet, connection, this);
  169. } else {
  170. // if authenticationFactor === 0, it means the server does not support
  171. // the multi-factor authentication capability
  172. if (this.authenticationFactor !== 0) {
  173. // if we are past the first authentication factor, we should use the
  174. // corresponding password (if there is one)
  175. connection.config.password =
  176. this[`password${this.authenticationFactor}`];
  177. // update the current authentication factor
  178. this.authenticationFactor += 1;
  179. }
  180. // if marker === 0x02, it means it is an AuthNextFactor packet,
  181. // which is similar in structure to an AuthSwitchRequest packet,
  182. // so, we can use it directly
  183. authSwitch.authSwitchRequest(packet, connection, this);
  184. }
  185. return ClientHandshake.prototype.handshakeResult;
  186. } catch (err) {
  187. // Authentication errors are fatal
  188. err.code = 'AUTH_SWITCH_PLUGIN_ERROR';
  189. err.fatal = true;
  190. if (this.onResult) {
  191. this.onResult(err);
  192. } else {
  193. this.emit('error', err);
  194. }
  195. return null;
  196. }
  197. }
  198. if (marker !== 0) {
  199. const err = new Error('Unexpected packet during handshake phase');
  200. // Unknown handshake errors are fatal
  201. err.code = 'HANDSHAKE_UNKNOWN_ERROR';
  202. err.fatal = true;
  203. if (this.onResult) {
  204. this.onResult(err);
  205. } else {
  206. this.emit('error', err);
  207. }
  208. return null;
  209. }
  210. // this should be called from ClientHandshake command only
  211. // and skipped when called from ChangeUser command
  212. if (!connection.authorized) {
  213. connection.authorized = true;
  214. if (connection.config.compress) {
  215. const enableCompression =
  216. require('../compressed_protocol.js').enableCompression;
  217. enableCompression(connection);
  218. }
  219. }
  220. if (this.onResult) {
  221. this.onResult(null);
  222. }
  223. return null;
  224. }
  225. }
  226. module.exports = ClientHandshake;