|
| 1 | +// Copyright (C) MongoDB, Inc. 2018-present. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 4 | +// not use this file except in compliance with the License. You may obtain |
| 5 | +// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | + |
| 7 | +package auth |
| 8 | + |
| 9 | +import ( |
| 10 | + "context" |
| 11 | + "fmt" |
| 12 | + |
| 13 | + "github.com/mongodb/mongo-go-driver/core/description" |
| 14 | + "github.com/mongodb/mongo-go-driver/core/wiremessage" |
| 15 | + "github.com/xdg/scram" |
| 16 | + "github.com/xdg/stringprep" |
| 17 | +) |
| 18 | + |
| 19 | +// SCRAMSHA256 is the mechanism name for SCRAM-SHA-256. |
| 20 | +const SCRAMSHA256 = "SCRAM-SHA-256" |
| 21 | + |
| 22 | +func newScramSHA256Authenticator(cred *Cred) (Authenticator, error) { |
| 23 | + passprep, err := stringprep.SASLprep.Prepare(cred.Password) |
| 24 | + if err != nil { |
| 25 | + return nil, newAuthError(fmt.Sprintf("error SASLprepping password '%s'", cred.Password), err) |
| 26 | + } |
| 27 | + client, err := scram.SHA256.NewClientUnprepped(cred.Username, passprep, "") |
| 28 | + if err != nil { |
| 29 | + return nil, newAuthError("error initializing SCRAM-SHA-256 client", err) |
| 30 | + } |
| 31 | + client.WithMinIterations(4096) |
| 32 | + return &ScramSHA256Authenticator{ |
| 33 | + DB: cred.Source, |
| 34 | + client: client, |
| 35 | + }, nil |
| 36 | +} |
| 37 | + |
| 38 | +// ScramSHA256Authenticator uses the SCRAM-SHA-256 algorithm over SASL to authenticate a connection. |
| 39 | +type ScramSHA256Authenticator struct { |
| 40 | + DB string |
| 41 | + client *scram.Client |
| 42 | +} |
| 43 | + |
| 44 | +// Auth authenticates the connection. |
| 45 | +func (a *ScramSHA256Authenticator) Auth(ctx context.Context, desc description.Server, rw wiremessage.ReadWriter) error { |
| 46 | + adapter := &scramSaslAdapter{conversation: a.client.NewConversation()} |
| 47 | + err := ConductSaslConversation(ctx, desc, rw, a.DB, adapter) |
| 48 | + if err != nil { |
| 49 | + return newAuthError("sasl conversation error", err) |
| 50 | + } |
| 51 | + return nil |
| 52 | +} |
| 53 | + |
| 54 | +type scramSaslAdapter struct { |
| 55 | + conversation *scram.ClientConversation |
| 56 | +} |
| 57 | + |
| 58 | +func (a *scramSaslAdapter) Start() (string, []byte, error) { |
| 59 | + step, err := a.conversation.Step("") |
| 60 | + if err != nil { |
| 61 | + return SCRAMSHA256, nil, err |
| 62 | + } |
| 63 | + return SCRAMSHA256, []byte(step), nil |
| 64 | +} |
| 65 | + |
| 66 | +func (a *scramSaslAdapter) Next(challenge []byte) ([]byte, error) { |
| 67 | + step, err := a.conversation.Step(string(challenge)) |
| 68 | + if err != nil { |
| 69 | + return nil, err |
| 70 | + } |
| 71 | + return []byte(step), nil |
| 72 | +} |
| 73 | + |
| 74 | +func (a *scramSaslAdapter) Completed() bool { |
| 75 | + return a.conversation.Done() |
| 76 | +} |
0 commit comments