1
// mgo - MongoDB driver for Go
3
// Copyright (c) 2010-2012 - Gustavo Niemeyer <gustavo@niemeyer.net>
5
// All rights reserved.
7
// Redistribution and use in source and binary forms, with or without
8
// modification, are permitted provided that the following conditions are met:
10
// 1. Redistributions of source code must retain the above copyright notice, this
11
// list of conditions and the following disclaimer.
12
// 2. Redistributions in binary form must reproduce the above copyright notice,
13
// this list of conditions and the following disclaimer in the documentation
14
// and/or other materials provided with the distribution.
16
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
17
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
20
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37
"gopkg.in/mgo.v2/bson"
38
"gopkg.in/mgo.v2/internal/scram"
49
type startSaslCmd struct {
50
StartSASL int `bson:"startSasl"`
53
type authResult struct {
58
type getNonceCmd struct {
62
type getNonceResult struct {
68
type logoutCmd struct {
73
Start int `bson:"saslStart,omitempty"`
74
Continue int `bson:"saslContinue,omitempty"`
75
ConversationId int `bson:"conversationId,omitempty"`
76
Mechanism string `bson:"mechanism,omitempty"`
80
type saslResult struct {
82
NotOk bool `bson:"code"` // Server <= 2.3.2 returns ok=1 & code>0 on errors (WTF?)
85
ConversationId int `bson:"conversationId"`
90
type saslStepper interface {
91
Step(serverData []byte) (clientData []byte, done bool, err error)
95
func (socket *mongoSocket) getNonce() (nonce string, err error) {
97
for socket.cachedNonce == "" && socket.dead == nil {
98
debugf("Socket %p to %s: waiting for nonce", socket, socket.addr)
99
socket.gotNonce.Wait()
101
if socket.cachedNonce == "mongos" {
103
return "", errors.New("Can't authenticate with mongos; see http://j.mp/mongos-auth")
105
debugf("Socket %p to %s: got nonce", socket, socket.addr)
106
nonce, err = socket.cachedNonce, socket.dead
107
socket.cachedNonce = ""
115
func (socket *mongoSocket) resetNonce() {
116
debugf("Socket %p to %s: requesting a new nonce", socket, socket.addr)
118
op.query = &getNonceCmd{GetNonce: 1}
119
op.collection = "admin.$cmd"
121
op.replyFunc = func(err error, reply *replyOp, docNum int, docData []byte) {
123
socket.kill(errors.New("getNonce: "+err.Error()), true)
126
result := &getNonceResult{}
127
err = bson.Unmarshal(docData, &result)
129
socket.kill(errors.New("Failed to unmarshal nonce: "+err.Error()), true)
132
debugf("Socket %p to %s: nonce unmarshalled: %#v", socket, socket.addr, result)
133
if result.Code == 13390 {
134
// mongos doesn't yet support auth (see http://j.mp/mongos-auth)
135
result.Nonce = "mongos"
136
} else if result.Nonce == "" {
138
if result.Err != "" {
139
msg = fmt.Sprintf("Got an empty nonce: %s (%d)", result.Err, result.Code)
141
msg = "Got an empty nonce"
143
socket.kill(errors.New(msg), true)
147
if socket.cachedNonce != "" {
149
panic("resetNonce: nonce already cached")
151
socket.cachedNonce = result.Nonce
152
socket.gotNonce.Signal()
155
err := socket.Query(op)
157
socket.kill(errors.New("resetNonce: "+err.Error()), true)
161
func (socket *mongoSocket) Login(cred Credential) error {
163
if cred.Mechanism == "" && socket.serverInfo.MaxWireVersion >= 3 {
164
cred.Mechanism = "SCRAM-SHA-1"
166
for _, sockCred := range socket.creds {
167
if sockCred == cred {
168
debugf("Socket %p to %s: login: db=%q user=%q (already logged in)", socket, socket.addr, cred.Source, cred.Username)
173
if socket.dropLogout(cred) {
174
debugf("Socket %p to %s: login: db=%q user=%q (cached)", socket, socket.addr, cred.Source, cred.Username)
175
socket.creds = append(socket.creds, cred)
181
debugf("Socket %p to %s: login: db=%q user=%q", socket, socket.addr, cred.Source, cred.Username)
184
switch cred.Mechanism {
185
case "", "MONGODB-CR", "MONGO-CR": // Name changed to MONGODB-CR in SERVER-8501.
186
err = socket.loginClassic(cred)
188
err = socket.loginPlain(cred)
190
err = socket.loginX509(cred)
192
// Try SASL for everything else, if it is available.
193
err = socket.loginSASL(cred)
197
debugf("Socket %p to %s: login error: %s", socket, socket.addr, err)
199
debugf("Socket %p to %s: login successful", socket, socket.addr)
204
func (socket *mongoSocket) loginClassic(cred Credential) error {
205
// Note that this only works properly because this function is
206
// synchronous, which means the nonce won't get reset while we're
207
// using it and any other login requests will block waiting for a
208
// new nonce provided in the defer call below.
209
nonce, err := socket.getNonce()
213
defer socket.resetNonce()
216
psum.Write([]byte(cred.Username + ":mongo:" + cred.Password))
219
ksum.Write([]byte(nonce + cred.Username))
220
ksum.Write([]byte(hex.EncodeToString(psum.Sum(nil))))
222
key := hex.EncodeToString(ksum.Sum(nil))
224
cmd := authCmd{Authenticate: 1, User: cred.Username, Nonce: nonce, Key: key}
226
return socket.loginRun(cred.Source, &cmd, &res, func() error {
228
return errors.New(res.ErrMsg)
231
socket.dropAuth(cred.Source)
232
socket.creds = append(socket.creds, cred)
238
type authX509Cmd struct {
244
func (socket *mongoSocket) loginX509(cred Credential) error {
245
cmd := authX509Cmd{Authenticate: 1, User: cred.Username, Mechanism: "MONGODB-X509"}
247
return socket.loginRun(cred.Source, &cmd, &res, func() error {
249
return errors.New(res.ErrMsg)
252
socket.dropAuth(cred.Source)
253
socket.creds = append(socket.creds, cred)
259
func (socket *mongoSocket) loginPlain(cred Credential) error {
260
cmd := saslCmd{Start: 1, Mechanism: "PLAIN", Payload: []byte("\x00" + cred.Username + "\x00" + cred.Password)}
262
return socket.loginRun(cred.Source, &cmd, &res, func() error {
264
return errors.New(res.ErrMsg)
267
socket.dropAuth(cred.Source)
268
socket.creds = append(socket.creds, cred)
274
func (socket *mongoSocket) loginSASL(cred Credential) error {
277
if cred.Mechanism == "SCRAM-SHA-1" {
278
// SCRAM is handled without external libraries.
279
sasl = saslNewScram(cred)
280
} else if len(cred.ServiceHost) > 0 {
281
sasl, err = saslNew(cred, cred.ServiceHost)
283
sasl, err = saslNew(cred, socket.Server().Addr)
290
// The goal of this logic is to carry a locked socket until the
291
// local SASL step confirms the auth is valid; the socket needs to be
292
// locked so that concurrent action doesn't leave the socket in an
293
// auth state that doesn't reflect the operations that took place.
294
// As a simple case, imagine inverting login=>logout to logout=>login.
296
// The logic below works because the lock func isn't called concurrently.
298
lock := func(b bool) {
316
payload, done, err := sasl.Step(res.Payload)
320
if done && res.Done {
321
socket.dropAuth(cred.Source)
322
socket.creds = append(socket.creds, cred)
330
ConversationId: res.ConversationId,
331
Mechanism: cred.Mechanism,
335
err = socket.loginRun(cred.Source, &cmd, &res, func() error {
336
// See the comment on lock for why this is necessary.
338
if !res.Ok || res.NotOk {
339
return fmt.Errorf("server returned error on SASL authentication step: %s", res.ErrMsg)
346
if done && res.Done {
347
socket.dropAuth(cred.Source)
348
socket.creds = append(socket.creds, cred)
356
func saslNewScram(cred Credential) *saslScram {
358
credsum.Write([]byte(cred.Username + ":mongo:" + cred.Password))
359
client := scram.NewClient(sha1.New, cred.Username, hex.EncodeToString(credsum.Sum(nil)))
360
return &saslScram{cred: cred, client: client}
363
type saslScram struct {
368
func (s *saslScram) Close() {}
370
func (s *saslScram) Step(serverData []byte) (clientData []byte, done bool, err error) {
371
more := s.client.Step(serverData)
372
return s.client.Out(), !more, s.client.Err()
375
func (socket *mongoSocket) loginRun(db string, query, result interface{}, f func() error) error {
382
op.collection = db + ".$cmd"
384
op.replyFunc = func(err error, reply *replyOp, docNum int, docData []byte) {
392
err = bson.Unmarshal(docData, result)
396
// Must handle this within the read loop for the socket, so
397
// that concurrent login requests are properly ordered.
402
err := socket.Query(&op)
406
mutex.Lock() // Wait.
410
func (socket *mongoSocket) Logout(db string) {
412
cred, found := socket.dropAuth(db)
414
debugf("Socket %p to %s: logout: db=%q (flagged)", socket, socket.addr, db)
415
socket.logout = append(socket.logout, cred)
420
func (socket *mongoSocket) LogoutAll() {
422
if l := len(socket.creds); l > 0 {
423
debugf("Socket %p to %s: logout all (flagged %d)", socket, socket.addr, l)
424
socket.logout = append(socket.logout, socket.creds...)
425
socket.creds = socket.creds[0:0]
430
func (socket *mongoSocket) flushLogout() (ops []interface{}) {
432
if l := len(socket.logout); l > 0 {
433
debugf("Socket %p to %s: logout all (flushing %d)", socket, socket.addr, l)
434
for i := 0; i != l; i++ {
436
op.query = &logoutCmd{1}
437
op.collection = socket.logout[i].Source + ".$cmd"
439
ops = append(ops, &op)
441
socket.logout = socket.logout[0:0]
447
func (socket *mongoSocket) dropAuth(db string) (cred Credential, found bool) {
448
for i, sockCred := range socket.creds {
449
if sockCred.Source == db {
450
copy(socket.creds[i:], socket.creds[i+1:])
451
socket.creds = socket.creds[:len(socket.creds)-1]
452
return sockCred, true
458
func (socket *mongoSocket) dropLogout(cred Credential) (found bool) {
459
for i, sockCred := range socket.logout {
460
if sockCred == cred {
461
copy(socket.logout[i:], socket.logout[i+1:])
462
socket.logout = socket.logout[:len(socket.logout)-1]