2019-06-18 14:28:30 +00:00
|
|
|
package xmpp
|
2016-01-06 15:51:12 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/base64"
|
|
|
|
"encoding/xml"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
2019-06-26 15:14:52 +00:00
|
|
|
|
|
|
|
"gosrc.io/xmpp/stanza"
|
2016-01-06 15:51:12 +00:00
|
|
|
)
|
|
|
|
|
2019-06-26 15:14:52 +00:00
|
|
|
func authSASL(socket io.ReadWriter, decoder *xml.Decoder, f stanza.StreamFeatures, user string, password string) (err error) {
|
2016-01-06 15:51:12 +00:00
|
|
|
// TODO: Implement other type of SASL Authentication
|
|
|
|
havePlain := false
|
|
|
|
for _, m := range f.Mechanisms.Mechanism {
|
|
|
|
if m == "PLAIN" {
|
|
|
|
havePlain = true
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if !havePlain {
|
2019-06-07 13:23:23 +00:00
|
|
|
err := fmt.Errorf("PLAIN authentication is not supported by server: %v", f.Mechanisms.Mechanism)
|
|
|
|
return NewConnError(err, true)
|
2016-01-06 15:51:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return authPlain(socket, decoder, user, password)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Plain authentication: send base64-encoded \x00 user \x00 password
|
|
|
|
func authPlain(socket io.ReadWriter, decoder *xml.Decoder, user string, password string) error {
|
|
|
|
raw := "\x00" + user + "\x00" + password
|
|
|
|
enc := make([]byte, base64.StdEncoding.EncodedLen(len(raw)))
|
|
|
|
base64.StdEncoding.Encode(enc, []byte(raw))
|
2019-06-26 15:14:52 +00:00
|
|
|
fmt.Fprintf(socket, "<auth xmlns='%s' mechanism='PLAIN'>%s</auth>", stanza.NSSASL, enc)
|
2016-01-06 15:51:12 +00:00
|
|
|
|
|
|
|
// Next message should be either success or failure.
|
2019-06-26 15:14:52 +00:00
|
|
|
val, err := stanza.NextPacket(decoder)
|
2016-01-06 15:51:12 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
switch v := val.(type) {
|
2019-06-26 15:14:52 +00:00
|
|
|
case stanza.SASLSuccess:
|
|
|
|
case stanza.SASLFailure:
|
2016-01-06 15:51:12 +00:00
|
|
|
// v.Any is type of sub-element in failure, which gives a description of what failed.
|
2019-06-07 13:23:23 +00:00
|
|
|
err := errors.New("auth failure: " + v.Any.Local)
|
|
|
|
return NewConnError(err, true)
|
2016-01-06 15:51:12 +00:00
|
|
|
default:
|
2018-01-13 17:50:17 +00:00
|
|
|
return errors.New("expected SASL success or failure, got " + v.Name())
|
2016-01-06 15:51:12 +00:00
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|