sasl.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. 'use strict'
  2. const crypto = require('./utils')
  3. function startSession(mechanisms) {
  4. if (mechanisms.indexOf('SCRAM-SHA-256') === -1) {
  5. throw new Error('SASL: Only mechanism SCRAM-SHA-256 is currently supported')
  6. }
  7. const clientNonce = crypto.randomBytes(18).toString('base64')
  8. return {
  9. mechanism: 'SCRAM-SHA-256',
  10. clientNonce,
  11. response: 'n,,n=*,r=' + clientNonce,
  12. message: 'SASLInitialResponse',
  13. }
  14. }
  15. async function continueSession(session, password, serverData) {
  16. if (session.message !== 'SASLInitialResponse') {
  17. throw new Error('SASL: Last message was not SASLInitialResponse')
  18. }
  19. if (typeof password !== 'string') {
  20. throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string')
  21. }
  22. if (password === '') {
  23. throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a non-empty string')
  24. }
  25. if (typeof serverData !== 'string') {
  26. throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a string')
  27. }
  28. const sv = parseServerFirstMessage(serverData)
  29. if (!sv.nonce.startsWith(session.clientNonce)) {
  30. throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce')
  31. } else if (sv.nonce.length === session.clientNonce.length) {
  32. throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short')
  33. }
  34. var clientFirstMessageBare = 'n=*,r=' + session.clientNonce
  35. var serverFirstMessage = 'r=' + sv.nonce + ',s=' + sv.salt + ',i=' + sv.iteration
  36. var clientFinalMessageWithoutProof = 'c=biws,r=' + sv.nonce
  37. var authMessage = clientFirstMessageBare + ',' + serverFirstMessage + ',' + clientFinalMessageWithoutProof
  38. var saltBytes = Buffer.from(sv.salt, 'base64')
  39. var saltedPassword = await crypto.deriveKey(password, saltBytes, sv.iteration)
  40. var clientKey = await crypto.hmacSha256(saltedPassword, 'Client Key')
  41. var storedKey = await crypto.sha256(clientKey)
  42. var clientSignature = await crypto.hmacSha256(storedKey, authMessage)
  43. var clientProof = xorBuffers(Buffer.from(clientKey), Buffer.from(clientSignature)).toString('base64')
  44. var serverKey = await crypto.hmacSha256(saltedPassword, 'Server Key')
  45. var serverSignatureBytes = await crypto.hmacSha256(serverKey, authMessage)
  46. session.message = 'SASLResponse'
  47. session.serverSignature = Buffer.from(serverSignatureBytes).toString('base64')
  48. session.response = clientFinalMessageWithoutProof + ',p=' + clientProof
  49. }
  50. function finalizeSession(session, serverData) {
  51. if (session.message !== 'SASLResponse') {
  52. throw new Error('SASL: Last message was not SASLResponse')
  53. }
  54. if (typeof serverData !== 'string') {
  55. throw new Error('SASL: SCRAM-SERVER-FINAL-MESSAGE: serverData must be a string')
  56. }
  57. const { serverSignature } = parseServerFinalMessage(serverData)
  58. if (serverSignature !== session.serverSignature) {
  59. throw new Error('SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match')
  60. }
  61. }
  62. /**
  63. * printable = %x21-2B / %x2D-7E
  64. * ;; Printable ASCII except ",".
  65. * ;; Note that any "printable" is also
  66. * ;; a valid "value".
  67. */
  68. function isPrintableChars(text) {
  69. if (typeof text !== 'string') {
  70. throw new TypeError('SASL: text must be a string')
  71. }
  72. return text
  73. .split('')
  74. .map((_, i) => text.charCodeAt(i))
  75. .every((c) => (c >= 0x21 && c <= 0x2b) || (c >= 0x2d && c <= 0x7e))
  76. }
  77. /**
  78. * base64-char = ALPHA / DIGIT / "/" / "+"
  79. *
  80. * base64-4 = 4base64-char
  81. *
  82. * base64-3 = 3base64-char "="
  83. *
  84. * base64-2 = 2base64-char "=="
  85. *
  86. * base64 = *base64-4 [base64-3 / base64-2]
  87. */
  88. function isBase64(text) {
  89. return /^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(text)
  90. }
  91. function parseAttributePairs(text) {
  92. if (typeof text !== 'string') {
  93. throw new TypeError('SASL: attribute pairs text must be a string')
  94. }
  95. return new Map(
  96. text.split(',').map((attrValue) => {
  97. if (!/^.=/.test(attrValue)) {
  98. throw new Error('SASL: Invalid attribute pair entry')
  99. }
  100. const name = attrValue[0]
  101. const value = attrValue.substring(2)
  102. return [name, value]
  103. })
  104. )
  105. }
  106. function parseServerFirstMessage(data) {
  107. const attrPairs = parseAttributePairs(data)
  108. const nonce = attrPairs.get('r')
  109. if (!nonce) {
  110. throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing')
  111. } else if (!isPrintableChars(nonce)) {
  112. throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce must only contain printable characters')
  113. }
  114. const salt = attrPairs.get('s')
  115. if (!salt) {
  116. throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing')
  117. } else if (!isBase64(salt)) {
  118. throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64')
  119. }
  120. const iterationText = attrPairs.get('i')
  121. if (!iterationText) {
  122. throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing')
  123. } else if (!/^[1-9][0-9]*$/.test(iterationText)) {
  124. throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration count')
  125. }
  126. const iteration = parseInt(iterationText, 10)
  127. return {
  128. nonce,
  129. salt,
  130. iteration,
  131. }
  132. }
  133. function parseServerFinalMessage(serverData) {
  134. const attrPairs = parseAttributePairs(serverData)
  135. const serverSignature = attrPairs.get('v')
  136. if (!serverSignature) {
  137. throw new Error('SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing')
  138. } else if (!isBase64(serverSignature)) {
  139. throw new Error('SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature must be base64')
  140. }
  141. return {
  142. serverSignature,
  143. }
  144. }
  145. function xorBuffers(a, b) {
  146. if (!Buffer.isBuffer(a)) {
  147. throw new TypeError('first argument must be a Buffer')
  148. }
  149. if (!Buffer.isBuffer(b)) {
  150. throw new TypeError('second argument must be a Buffer')
  151. }
  152. if (a.length !== b.length) {
  153. throw new Error('Buffer lengths must match')
  154. }
  155. if (a.length === 0) {
  156. throw new Error('Buffers cannot be empty')
  157. }
  158. return Buffer.from(a.map((_, i) => a[i] ^ b[i]))
  159. }
  160. module.exports = {
  161. startSession,
  162. continueSession,
  163. finalizeSession,
  164. }