1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
|
// The MIT License
//
// Copyright (c) 2019 Proton Technologies AG
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package srp
import (
"bytes"
"encoding/base64"
"errors"
"math/big"
"crypto/rand"
"github.com/ProtonMail/go-crypto/openpgp"
"github.com/ProtonMail/go-crypto/openpgp/clearsign"
"github.com/cronokirby/saferith"
)
var (
// ErrDataAfterModulus found extra data after decode the modulus
ErrDataAfterModulus = errors.New("pm-srp: extra data after modulus")
// ErrInvalidSignature invalid modulus signature
ErrInvalidSignature = errors.New("pm-srp: invalid modulus signature")
RandReader = rand.Reader
)
// Store random reader in a variable to be able to overwrite it in tests
// Proofs Srp Proofs object. Changed SrpProofs to Proofs because the name will be used as srp.SrpProofs by other packages and as SrpSrpProofs on mobile
// ClientProof []byte client proof
// ClientEphemeral []byte calculated from
// ExpectedServerProof []byte
type Proofs struct {
ClientProof, ClientEphemeral, ExpectedServerProof, sharedSession []byte
}
// Auth stores byte data for the calculation of SRP proofs.
// * Changed SrpAuto to Auth because the name will be used as srp.SrpAuto by other packages and as SrpSrpAuth on mobile
// * Also the data from the API called Auth. it could be match the meaning and reduce the confusion
type Auth struct {
Modulus, ServerEphemeral, HashedPassword []byte
Version int
}
// Amored pubkey for modulus verification
const modulusPubkey = "-----BEGIN PGP PUBLIC KEY BLOCK-----\r\n\r\nxjMEXAHLgxYJKwYBBAHaRw8BAQdAFurWXXwjTemqjD7CXjXVyKf0of7n9Ctm\r\nL8v9enkzggHNEnByb3RvbkBzcnAubW9kdWx1c8J3BBAWCgApBQJcAcuDBgsJ\r\nBwgDAgkQNQWFxOlRjyYEFQgKAgMWAgECGQECGwMCHgEAAPGRAP9sauJsW12U\r\nMnTQUZpsbJb53d0Wv55mZIIiJL2XulpWPQD/V6NglBd96lZKBmInSXX/kXat\r\nSv+y0io+LR8i2+jV+AbOOARcAcuDEgorBgEEAZdVAQUBAQdAeJHUz1c9+KfE\r\nkSIgcBRE3WuXC4oj5a2/U3oASExGDW4DAQgHwmEEGBYIABMFAlwBy4MJEDUF\r\nhcTpUY8mAhsMAAD/XQD8DxNI6E78meodQI+wLsrKLeHn32iLvUqJbVDhfWSU\r\nWO4BAMcm1u02t4VKw++ttECPt+HUgPUq5pqQWe5Q2cW4TMsE\r\n=Y4Mw\r\n-----END PGP PUBLIC KEY BLOCK-----"
// readClearSignedMessage reads the clear text from signed message and verifies
// signature. There must be no data appended after signed message in input string.
// The message must be sign by key corresponding to `modulusPubkey`.
func readClearSignedMessage(signedMessage string) (string, error) {
modulusBlock, rest := clearsign.Decode([]byte(signedMessage))
if len(rest) != 0 {
return "", ErrDataAfterModulus
}
modulusKeyring, err := openpgp.ReadArmoredKeyRing(bytes.NewReader([]byte(modulusPubkey)))
if err != nil {
return "", errors.New("pm-srp: can not read modulus pubkey")
}
_, err = openpgp.CheckDetachedSignature(modulusKeyring, bytes.NewReader(modulusBlock.Bytes), modulusBlock.ArmoredSignature.Body, nil)
if err != nil {
return "", ErrInvalidSignature
}
return string(modulusBlock.Bytes), nil
}
func GetModulusKey() string {
return modulusPubkey
}
// NewAuth Creates new Auth from strings input. Salt and server ephemeral are in
// base64 format. Modulus is base64 with signature attached. The signature is
// verified against server key. The version controls password hash algorithm.
//
// Parameters:
// - version int: The *x* component of the vector.
// - username string: The *y* component of the vector.
// - password []byte: The *z* component of the vector.
// - b64salt string: The std-base64 formatted salt
// Returns:
// - auth *Auth: the pre calculated auth information
// - err error: throw error
// Usage:
//
// Warnings:
// - Be careful! Poos can hurt.
func NewAuth(version int, username string, password []byte, b64salt, signedModulus, serverEphemeral string) (auth *Auth, err error) {
data := &Auth{}
// Modulus
var modulus string
modulus, err = readClearSignedMessage(signedModulus)
if err != nil {
return
}
data.Modulus, err = base64.StdEncoding.DecodeString(modulus)
if err != nil {
return
}
// Password
var decodedSalt []byte
if version >= 3 {
decodedSalt, err = base64.StdEncoding.DecodeString(b64salt)
if err != nil {
return
}
}
data.HashedPassword, err = HashPassword(version, password, username, decodedSalt, data.Modulus)
if err != nil {
return
}
// Server ephermeral
data.ServerEphemeral, err = base64.StdEncoding.DecodeString(serverEphemeral)
if err != nil {
return
}
// Authentication version
data.Version = version
auth = data
return
}
// NewAuthForVerifier Creates new Auth from strings input. Salt and server ephemeral are in
// base64 format. Modulus is base64 with signature attached. The signature is
// verified against server key. The version controls password hash algorithm.
//
// Parameters:
// - version int: The *x* component of the vector.
// - username string: The *y* component of the vector.
// - password []byte: The *z* component of the vector.
// - salt string:
// Returns:
// - auth *Auth: the pre calculated auth information
// - err error: throw error
// Usage:
//
// Warnings:
// - none.
func NewAuthForVerifier(password []byte, signedModulus string, rawSalt []byte) (auth *Auth, err error) {
data := &Auth{}
// Modulus
var modulus string
modulus, err = readClearSignedMessage(signedModulus)
if err != nil {
return
}
data.Modulus, err = base64.StdEncoding.DecodeString(modulus)
if err != nil {
return
}
// hash version is 4
data.HashedPassword, err = hashPasswordVersion3(password, rawSalt, data.Modulus)
if err != nil {
return
}
// Authentication version hardcoded
data.Version = 4
auth = data
return
}
func toInt(arr []byte) *big.Int {
var reversed = make([]byte, len(arr))
for i := 0; i < len(arr); i++ {
reversed[len(arr)-i-1] = arr[i]
}
return big.NewInt(0).SetBytes(reversed)
}
func fromInt(bitLength int, num *big.Int) []byte {
var arr = num.Bytes()
var reversed = make([]byte, bitLength/8)
for i := 0; i < len(arr); i++ {
reversed[len(arr)-i-1] = arr[i]
}
return reversed
}
func toNat(arr []byte) *saferith.Nat {
var reversed = make([]byte, len(arr))
for i := 0; i < len(arr); i++ {
reversed[len(arr)-i-1] = arr[i]
}
return new(saferith.Nat).SetBytes(reversed)
}
func newNat(val uint64) *saferith.Nat {
return new(saferith.Nat).SetUint64(val)
}
func toModulus(arr []byte) *saferith.Modulus {
var reversed = make([]byte, len(arr))
for i := 0; i < len(arr); i++ {
reversed[len(arr)-i-1] = arr[i]
}
return saferith.ModulusFromBytes(reversed)
}
func fromNat(bitLength int, nat *saferith.Nat) []byte {
var arr = nat.Bytes()
var reversed = make([]byte, bitLength/8)
for i := 0; i < len(arr); i++ {
reversed[len(arr)-i-1] = arr[i]
}
return reversed
}
func computeMultiplier(generator, modulus *big.Int, bitLength int) (*saferith.Nat, error) {
modulusMinusOne := big.NewInt(0).Sub(modulus, big.NewInt(1))
multiplier := toInt(expandHash(append(fromInt(bitLength, generator), fromInt(bitLength, modulus)...)))
multiplier = multiplier.Mod(multiplier, modulus)
if multiplier.Cmp(big.NewInt(1)) <= 0 || multiplier.Cmp(modulusMinusOne) >= 0 {
return nil, errors.New("pm-srp: SRP multiplier is out of bounds")
}
return new(saferith.Nat).SetBig(multiplier, bitLength), nil
}
func checkParams(bitLength int, ephemeral, generator, modulus *big.Int) error {
if !generator.IsInt64() || generator.Int64() != 2 {
return errors.New("go-srp: SRP generator must always be 2")
}
if modulus.BitLen() != bitLength {
return errors.New("go-srp: SRP modulus has incorrect size")
}
if modulus.Bit(0) != 1 || modulus.Bit(1) != 1 || modulus.Bit(2) != 0 {
// By quadratic reciprocity, 2 is a square mod N if and only if
// N is 1 or 7 mod 8. We want the generator, 2, to generate the
// whole group, not just the prime-order subgroup, so it should
// *not* be a square. In addition, since N should be prime, it
// must not be even, and since (N-1)/2 should be prime, N must
// not be 1 mod 4. This leaves 3 mod 8 as the only option.
return errors.New("go-srp: SRP modulus is not 3 mod 8")
}
modulusMinusOne := big.NewInt(0).Sub(modulus, big.NewInt(1))
if ephemeral.Cmp(big.NewInt(1)) <= 0 || ephemeral.Cmp(modulusMinusOne) >= 0 {
return errors.New("go-srp: SRP server ephemeral is out of bounds")
}
// halfModulus is (N-1)/2. We've already checked that N is odd.
halfModulus := big.NewInt(0).Rsh(modulus, 1)
// Check safe primality
if !halfModulus.ProbablyPrime(10) {
return errors.New("pm-srp: SRP modulus is not a safe prime")
}
// Check primality using the Lucas primality test. This requires a
// single exponentiation for complete confidence (assuming halfModulus
// is prime), and so is much more efficient than relying on ProbablyPrime.
// To prove primality with the Lucas test with base 2, it suffices to
// show that 2^(N-1) = 1 (mod N) and 2^((N-1)/2) != 1 (mod N). The stricter
// condition, that 2^((N-1)/2) = -1 (mod N), is a single exponentiation
// and doubles as a test / guarantee that 2 is a generator of the whole group
// (and not a square).
if big.NewInt(0).Exp(generator, halfModulus, modulus).Cmp(modulusMinusOne) != 0 {
return errors.New("pm-srp: SRP modulus is not prime")
}
return nil
}
func generateClientEphemeral(
bitLength int,
modulusInt, modulusMinusOneInt *big.Int,
modulusMinusOneNat *saferith.Nat,
modulus *saferith.Modulus,
) (secret *saferith.Nat, ephemeral []byte, err error) {
var secretInt *big.Int
var secretBytes []byte
lowerBoundNat := newNat(uint64(bitLength * 2))
for {
secretInt, err = rand.Int(RandReader, modulusMinusOneInt)
if err != nil {
return nil, nil, err
}
secretBytes = fromInt(bitLength, secretInt)
secret = toNat(secretBytes)
// Prevent g^a from being smaller than the modulus
// and a to be >= than N-1
notTooSmall, _, _ := secret.Cmp(lowerBoundNat)
_, _, notTooLarge := secret.Cmp(modulusMinusOneNat)
if notTooSmall == 1 && notTooLarge == 1 {
break
}
}
ephemeralNat := new(saferith.Nat).Exp(newNat(2), secret, modulus)
ephemeral = fromNat(bitLength, ephemeralNat)
return secret, ephemeral, nil
}
func computeScrambleParam(clientEphemeralBytes, serverEphemeralBytes []byte) *saferith.Nat {
return toNat(
expandHash(
append(
clientEphemeralBytes,
serverEphemeralBytes...,
),
),
)
}
func computeBaseClientSide(hashedPassword, generator, serverEphemeral, multiplier *saferith.Nat, modulus *saferith.Modulus) *saferith.Nat {
var receiver saferith.Nat
return receiver.ModSub(
serverEphemeral,
receiver.ModMul(
receiver.Exp(
generator,
hashedPassword,
modulus,
),
multiplier,
modulus,
),
modulus,
)
}
func computeExponentClientSide(bitLength int, scramblingParam, hashedPassword, clientSecret *saferith.Nat, modulusMinusOne *saferith.Modulus) *saferith.Nat {
var receiver saferith.Nat
return receiver.ModAdd(
receiver.ModMul(
scramblingParam,
hashedPassword,
modulusMinusOne,
),
clientSecret,
modulusMinusOne,
)
}
func computeSharedSecretClientSide(
bitLength int,
hashedPassword, generator, serverEphemeral, multiplier, modulusMinusOneNat, clientSecret, scramblingParam *saferith.Nat,
modulus *saferith.Modulus,
) []byte {
base := computeBaseClientSide(
hashedPassword,
generator,
serverEphemeral,
multiplier,
modulus,
)
modulusMinusOne := saferith.ModulusFromNat(modulusMinusOneNat)
exponent := computeExponentClientSide(
bitLength,
scramblingParam,
hashedPassword,
clientSecret,
modulusMinusOne,
)
sharedSession := new(saferith.Nat).Exp(
base,
exponent,
modulus,
)
return fromNat(bitLength, sharedSession)
}
func computeClientProof(clientEphemeral, serverEphemeral, sharedSecret []byte) []byte {
return expandHash(
bytes.Join(
[][]byte{
clientEphemeral,
serverEphemeral,
sharedSecret,
},
[]byte{},
),
)
}
func computeServerProof(clientEphemeral, clientProof, sharedSecret []byte) []byte {
return expandHash(
bytes.Join(
[][]byte{
clientEphemeral,
clientProof,
sharedSecret,
},
[]byte{},
),
)
}
// GenerateProofs calculates SPR proofs.
func (s *Auth) GenerateProofs(bitLength int) (*Proofs, error) {
serverEphemeralInt := toInt(s.ServerEphemeral)
generatorInt := big.NewInt(2)
modulusInt := toInt(s.Modulus)
modulusMinusOneInt := big.NewInt(0).Sub(modulusInt, big.NewInt(1))
err := checkParams(
bitLength,
serverEphemeralInt,
generatorInt,
modulusInt,
)
if err != nil {
return nil, err
}
modulus := toModulus(s.Modulus)
modulusMinusOneNat := new(saferith.Nat).SetBig(modulusMinusOneInt, bitLength)
var clientSecret, scramblingParam *saferith.Nat
var clientEphemeralBytes []byte
for {
clientSecret, clientEphemeralBytes, err = generateClientEphemeral(
bitLength,
modulusInt, modulusMinusOneInt,
modulusMinusOneNat,
modulus,
)
if err != nil {
return nil, err
}
scramblingParam = computeScrambleParam(clientEphemeralBytes, s.ServerEphemeral)
if _, equal, _ := scramblingParam.Cmp(newNat(0)); equal != 1 { // Very likely
break
}
}
multiplierNat, err := computeMultiplier(generatorInt, modulusInt, bitLength)
if err != nil {
return nil, err
}
hashedPasswordNat := toNat(s.HashedPassword)
generatorNat := newNat(2)
serverEphemeralNat := toNat(s.ServerEphemeral)
sharedSecret := computeSharedSecretClientSide(
bitLength,
hashedPasswordNat,
generatorNat,
serverEphemeralNat,
multiplierNat,
modulusMinusOneNat,
clientSecret,
scramblingParam,
modulus,
)
clientProof := computeClientProof(clientEphemeralBytes, s.ServerEphemeral, sharedSecret)
serverProof := computeServerProof(clientEphemeralBytes, clientProof, sharedSecret)
proofs := &Proofs{
ClientEphemeral: clientEphemeralBytes,
ClientProof: clientProof,
ExpectedServerProof: serverProof,
sharedSession: sharedSecret,
}
return proofs, nil
}
// GenerateVerifier verifier for update pwds and create accounts
func (s *Auth) GenerateVerifier(bitLength int) ([]byte, error) {
modulus := toModulus(s.Modulus)
generator := newNat(2)
hashedPassword := toNat(s.HashedPassword)
calModPow := new(saferith.Nat).SetUint64(0).Exp(generator, hashedPassword, modulus)
return fromNat(bitLength, calModPow), nil
}
func RandomBits(bits int) ([]byte, error) {
return RandomBytes(bits / 8)
}
func RandomBytes(byes int) (raw []byte, err error) {
raw = make([]byte, byes)
_, err = rand.Read(raw)
return
}
|