forked from xmppo/go-xmpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxmpp.go
1805 lines (1490 loc) · 46.6 KB
/
xmpp.go
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// TODO(rsc):
// More precise error handling.
// Presence functionality.
// TODO(mattn):
// Add proxy authentication.
// Package xmpp implements a simple Google Talk client
// using the XMPP protocol described in RFC 3920 and RFC 3921.
package xmpp
import (
"bufio"
"bytes"
"crypto/hmac"
"crypto/md5" //nolint:gosec // go fuck yourself, gosec
"crypto/rand"
"crypto/sha1" //nolint:gosec // go fuck yourself, gosec
"crypto/sha256"
"crypto/sha512"
"crypto/tls"
"encoding/base64"
"encoding/binary"
"encoding/xml"
"errors"
"fmt"
"hash"
"io"
"math/big"
"net"
"net/http"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"time"
"golang.org/x/crypto/pbkdf2"
"golang.org/x/text/encoding/charmap"
)
const (
nsStream = "http://etherx.jabber.org/streams"
nsTLS = "urn:ietf:params:xml:ns:xmpp-tls"
nsSASL = "urn:ietf:params:xml:ns:xmpp-sasl"
nsBind = "urn:ietf:params:xml:ns:xmpp-bind"
nsClient = "jabber:client"
nsSession = "urn:ietf:params:xml:ns:xmpp-session"
)
// DefaultConfig is default TLS configuration options.
var DefaultConfig = &tls.Config{} //nolint:gosec // go fuck yourself, gosec
// DebugWriter is the writer used to write debugging output to.
var DebugWriter io.Writer = os.Stderr
var StanzaWriter io.Writer
// Cookie is a unique XMPP session identifier.
type Cookie uint64
func getCookie() Cookie {
var buf [8]byte
if _, err := rand.Reader.Read(buf[:]); err != nil {
panic("Failed to read random bytes: " + err.Error())
}
return Cookie(binary.LittleEndian.Uint64(buf[:]))
}
// Client holds XMPP connection options.
type Client struct {
conn net.Conn // connection to server
jid string // Jabber ID for our connection
domain string
p *xml.Decoder
}
func (c *Client) JID() string {
return c.jid
}
func containsIgnoreCase(s, substr string) bool {
s, substr = strings.ToUpper(s), strings.ToUpper(substr)
return strings.Contains(s, substr)
}
func connect(host, user, passwd string, timeout time.Duration) (net.Conn, error) {
addr := host
if strings.TrimSpace(host) == "" {
a := strings.SplitN(user, "@", 2)
if len(a) == 2 {
addr = a[1]
}
}
a := strings.SplitN(host, ":", 2)
if len(a) == 1 {
addr += ":5222"
}
proxy := os.Getenv("HTTP_PROXY")
if proxy == "" {
proxy = os.Getenv("http_proxy")
}
// test for no proxy, takes a comma separated list with substrings to match
if proxy != "" {
noproxy := os.Getenv("NO_PROXY")
if noproxy == "" {
noproxy = os.Getenv("no_proxy")
}
if noproxy != "" {
nplist := strings.Split(noproxy, ",")
for _, s := range nplist {
if containsIgnoreCase(addr, s) {
proxy = ""
break
}
}
}
}
if proxy != "" {
url, err := url.Parse(proxy)
if err == nil {
addr = url.Host
}
}
conn, err := net.DialTimeout("tcp", addr, timeout)
if err != nil {
return nil, err
}
if proxy != "" {
if _, err := fmt.Fprintf(conn, "CONNECT %s HTTP/1.1\r\n", host); err != nil {
return nil, err
}
if _, err := fmt.Fprintf(conn, "Host: %s\r\n", host); err != nil {
return nil, err
}
if _, err := fmt.Fprintf(conn, "\r\n"); err != nil {
return nil, err
}
br := bufio.NewReader(conn)
req, _ := http.NewRequest("CONNECT", host, nil) //nolint:noctx // In this case we don't care about context
resp, err := http.ReadResponse(br, req) //nolint:bodyclose // The point is NOT to close proxied connection
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
f := strings.SplitN(resp.Status, " ", 2)
return nil, errors.New(f[1])
}
}
return conn, nil
}
// Options are used to specify additional options for new clients, such as a Resource.
type Options struct {
// Host specifies what host to connect to, as either "hostname" or "hostname:port"
// If host is not specified, the DNS SRV should be used to find the host from the domainpart of the JID.
// Default the port to 5222.
Host string
// User specifies what user to authenticate to the remote server.
User string
// Password supplies the password to use for authentication with the remote server.
Password string
// DialTimeout is the time limit for establishing a connection. A
// DialTimeout of zero means no timeout.
DialTimeout time.Duration
// Resource specifies an XMPP client resource, like "bot", instead of accepting one
// from the server. Use "" to let the server generate one for your client.
Resource string
// OAuthScope provides go-xmpp the required scope for OAuth2 authentication.
OAuthScope string
// OAuthToken provides go-xmpp with the required OAuth2 token used to authenticate
OAuthToken string
// OAuthXmlNs provides go-xmpp with the required namespaced used for OAuth2 authentication. This is
// provided to the server as the xmlns:auth attribute of the OAuth2 authentication request.
OAuthXmlNs string
// TLS Config
TLSConfig *tls.Config
// InsecureAllowUnencryptedAuth permits authentication over a TCP connection that has not been promoted to
// TLS by STARTTLS; this could leak authentication information over the network, or permit man in the middle
// attacks.
InsecureAllowUnencryptedAuth bool
// NoTLS directs go-xmpp to not use TLS initially to contact the server; instead, a plain old unencrypted
// TCP connection should be used. (Can be combined with StartTLS to support STARTTLS-based servers.)
NoTLS bool
// StartTLS directs go-xmpp to STARTTLS if the server supports it; go-xmpp will automatically STARTTLS
// if the server requires it regardless of this option.
StartTLS bool
// Debug output
Debug bool
// Use server sessions
Session bool
// Presence Status
Status string
// Status message
StatusMessage string
}
// NewClient establishes a new Client connection based on a set of Options.
func (o Options) NewClient() (*Client, error) {
host := o.Host
if strings.TrimSpace(host) == "" {
a := strings.SplitN(o.User, "@", 2)
if len(a) == 2 {
if _, addrs, err := net.LookupSRV("xmpp-client", "tcp", a[1]); err == nil {
if len(addrs) > 0 {
// default to first record
host = fmt.Sprintf("%s:%d", addrs[0].Target, addrs[0].Port)
defP := addrs[0].Priority
for _, adr := range addrs {
if adr.Priority < defP {
host = fmt.Sprintf("%s:%d", adr.Target, adr.Port)
defP = adr.Priority
}
}
} else {
host = a[1]
}
} else {
host = a[1]
}
}
}
c, err := connect(host, o.User, o.Password, o.DialTimeout)
if err != nil {
return nil, err
}
if strings.LastIndex(host, ":") > 0 {
host = host[:strings.LastIndex(host, ":")]
}
client := new(Client)
if o.NoTLS {
client.conn = c
} else {
var tlsconn *tls.Conn
if o.TLSConfig != nil {
tlsconn = tls.Client(c, o.TLSConfig)
host = o.TLSConfig.ServerName
} else {
newconfig := DefaultConfig.Clone()
newconfig.ServerName = host
tlsconn = tls.Client(c, newconfig)
}
if err = tlsconn.Handshake(); err != nil {
return nil, err
}
insecureSkipVerify := DefaultConfig.InsecureSkipVerify
if o.TLSConfig != nil {
insecureSkipVerify = o.TLSConfig.InsecureSkipVerify
}
if !insecureSkipVerify {
if err = tlsconn.VerifyHostname(host); err != nil {
return nil, err
}
}
client.conn = tlsconn
}
if err := client.init(&o); err != nil {
return nil, err
}
return client, nil
}
// NewClient creates a new connection to a host given as "hostname" or "hostname:port".
// If host is not specified, the DNS SRV should be used to find the host from the domainpart of the JID.
// Default the port to 5222.
func NewClient(host, user, passwd string, debug bool) (*Client, error) {
opts := Options{
Host: host,
User: user,
Password: passwd,
Debug: debug,
Session: false,
}
return opts.NewClient()
}
// NewClientNoTLS creates a new client without TLS.
func NewClientNoTLS(host, user, passwd string, debug bool) (*Client, error) {
opts := Options{
Host: host,
User: user,
Password: passwd,
NoTLS: true,
Debug: debug,
Session: false,
}
return opts.NewClient()
}
// Close closes the XMPP connection.
func (c *Client) Close() error {
if c.conn != (*tls.Conn)(nil) {
return c.conn.Close()
}
return nil
}
func saslDigestResponse(username, realm, passwd, nonce, cnonceStr, authenticate, digestURI, nonceCountStr string) string {
h := func(text string) []byte {
h := md5.New() //nolint:gosec // go fuck yourself, gosec
h.Write([]byte(text))
return h.Sum(nil)
}
hex := func(bytes []byte) string {
return fmt.Sprintf("%x", bytes)
}
kd := func(secret, data string) []byte {
return h(secret + ":" + data)
}
a1 := string(h(username+":"+realm+":"+passwd)) + ":" + nonce + ":" + cnonceStr
a2 := authenticate + ":" + digestURI
response := hex(kd(hex(h(a1)), nonce+":"+nonceCountStr+":"+cnonceStr+":auth:"+hex(h(a2))))
return response
}
func cnonce() string {
randSize := big.NewInt(0)
randSize.Lsh(big.NewInt(1), 64)
cn, err := rand.Int(rand.Reader, randSize)
if err != nil {
return ""
}
return fmt.Sprintf("%016x", cn)
}
func (c *Client) init(o *Options) error {
var (
domain string
user string
)
a := strings.SplitN(o.User, "@", 2)
// Check if User is not empty. Otherwise, we'll be attempting ANONYMOUS with Host domain.
switch {
case len(o.User) > 0:
if len(a) != 2 {
return errors.New("xmpp: invalid username (want user@domain): " + o.User)
}
user = a[0]
domain = a[1]
case strings.Contains(o.Host, ":"):
domain = strings.SplitN(o.Host, ":", 2)[0]
default:
domain = o.Host
}
// Declare intent to be a jabber client and gather stream features.
f, err := c.startStream(o, domain)
if err != nil {
return err
}
// If the server requires we STARTTLS, attempt to do so.
if f, err = c.startTLSIfRequired(f, o, domain); err != nil {
return err
}
var (
mechanism string
serverSignature []byte
)
if o.User == "" && o.Password == "" {
foundAnonymous := false
for _, m := range f.Mechanisms.Mechanism {
if m == "ANONYMOUS" {
_, err := fmt.Fprintf(StanzaWriter, "<auth xmlns='%s' mechanism='ANONYMOUS' />\n", nsSASL)
if err != nil {
return err
}
foundAnonymous = true
break
}
}
if !foundAnonymous {
return fmt.Errorf("server does not allow ANONYMOUS authentication and username and password were not specified")
}
} else {
// Even digest forms of authentication are unsafe if we do not know that the host
// we are talking to is the actual server, and not a man in the middle playing
// proxy.
if !c.IsEncrypted() && !o.InsecureAllowUnencryptedAuth {
return errors.New("refusing to authenticate over unencrypted TCP connection")
}
mechanism = ""
for _, m := range f.Mechanisms.Mechanism {
switch m {
case "SCRAM-SHA-512":
mechanism = m
case "SCRAM-SHA-256":
if mechanism != "SCRAM-SHA-512" {
mechanism = m
}
case "SCRAM-SHA-1":
if mechanism != "SCRAM-SHA-512" &&
mechanism != "SCRAM-SHA-256" {
mechanism = m
}
case "X-OAUTH2":
if mechanism == "" {
mechanism = m
}
case "PLAIN":
if mechanism == "" {
mechanism = m
}
case "DIGEST-MD5":
if mechanism == "" {
mechanism = m
}
}
}
if strings.HasPrefix(mechanism, "SCRAM-SHA") {
// So here we are. XMPP folks "moved to historical" digest-md5 method
// https://datatracker.ietf.org/doc/html/rfc6331
// Looks like beacause of security shiteaters squealing about md5 "insecurity". And instead of peeing
// against winds, xmpp.org decide to deprecate digest mechanics and use scram, it is here anyway, so why
// not? Wise decision, kind of. But sooner or later "pseudo-security fanboys" will begin their raid against
// this already-not-so-new scram-thing. In-fact, they already abuse sha1,
// https://datatracker.ietf.org/doc/html/rfc6194
// Authentication can be considered relatively secure even via plain mechanism only via properly encrypted
// communication, leave this security thing to ssl. Do not try to invent secure auth via unencryped
// communication channels, it is labour of Sisyphus. Anyway, enough of rant.
var shaNewFn func() hash.Hash
// SCRAM-SHA256 vaguely described in https://datatracker.ietf.org/doc/html/rfc7677 which is main document
// for SCRAM-SHA* implementation. So we have to use more detailed description on
// https://wiki.xmpp.org/web/SASL_Authentication_and_SCRAM as reference.
switch mechanism {
case "SCRAM-SHA-512":
shaNewFn = sha512.New
case "SCRAM-SHA-256":
shaNewFn = sha256.New
case "SCRAM-SHA-1":
shaNewFn = sha1.New
default:
return errors.New("unsupported auth mechanism")
}
// 1. Normalization of utf-8 strings, namely - password, to avoid any variations that utf-8 allows.
// Normalization requirements described there, in common terms https://datatracker.ietf.org/doc/html/rfc4013
// We miss it here because this task is tedious/difficult to perform completely. So we absolutely trust in
// copy-paste :)
// 2. Pick a random string
clientNonce := cnonce()
// 3. Prepare initial message.
initialMessage := fmt.Sprintf("n=%s,r=%s", user, clientNonce)
// 4. The client prepends the GS2 header ("n,,"). Base64 it and send to server.
initialMessageGS2 := []byte("n,," + initialMessage)
b64Buffer := base64.StdEncoding.EncodeToString(initialMessageGS2)
_, err := fmt.Fprintf(
StanzaWriter,
"<auth xmlns='%s' mechanism='%s'>%s</auth>",
nsSASL,
mechanism,
b64Buffer,
)
if err != nil {
return err
}
// 5. The server responds with a challenge. The data of the challenge is base64 encoded.
var sfm string
if err = c.p.DecodeElement(&sfm, nil); err != nil {
return errors.New("unmarshal <challenge>: " + err.Error())
}
// 6. The client base64 decodes it.
b, err := base64.StdEncoding.DecodeString(sfm)
if err != nil {
return err
}
// 7. The client parses it decoded string.
// Here we have
// r as serverNonce
// s as salt
// i as iterations
var (
serverNonce string
salt []byte
iterations int
)
for _, serverReply := range strings.Split(string(b), ",") {
switch {
case strings.HasPrefix(serverReply, "r="):
serverNonce = strings.SplitN(serverReply, "=", 2)[1]
if !strings.HasPrefix(serverNonce, clientNonce) {
return errors.New("SCRAM: server nonce didn't start with client nonce")
}
case strings.HasPrefix(serverReply, "s="):
salt, err = base64.StdEncoding.DecodeString(strings.SplitN(serverReply, "=", 2)[1])
if err != nil {
return err
}
if string(salt) == "" {
return errors.New("SCRAM: server sent empty salt")
}
case strings.HasPrefix(serverReply, "i="):
iterations, err = strconv.Atoi(strings.SplitN(serverReply,
"=", 2)[1])
if err != nil {
return err
}
default:
return errors.New("unexpected conted in SCRAM challenge")
}
}
// 8. The client computes parameters for its final message
var (
clientFinalMessageBare = fmt.Sprintf("c=biws,r=%s", serverNonce)
saltedPassword = pbkdf2.Key([]byte(o.Password), salt, iterations, shaNewFn().Size(), shaNewFn)
h = hmac.New(shaNewFn, saltedPassword)
)
if _, err = h.Write([]byte("Client Key")); err != nil {
return err
}
clientKey := h.Sum(nil)
h.Reset()
var storedKey []byte
switch mechanism {
case "SCRAM-SHA-512":
storedKey512 := sha512.Sum512(clientKey)
storedKey = storedKey512[:]
case "SCRAM-SHA-256":
storedKey256 := sha256.Sum256(clientKey)
storedKey = storedKey256[:]
case "SCRAM-SHA-1":
storedKey1 := sha1.Sum(clientKey) //nolint:gosec // fuck yourself, gosec
storedKey = storedKey1[:]
}
if _, err = h.Write([]byte("Server Key")); err != nil {
return err
}
serverFirstMessage, err := base64.StdEncoding.DecodeString(sfm)
if err != nil {
return err
}
authMessage := fmt.Sprintf(
"%s,%s,%s",
initialMessage,
string(serverFirstMessage),
clientFinalMessageBare,
)
h = hmac.New(shaNewFn, storedKey)
if _, err = h.Write([]byte(authMessage)); err != nil {
return err
}
clientSignature := h.Sum(nil)
h.Reset()
if len(clientKey) != len(clientSignature) {
return errors.New("SCRAM: client key and signature length mismatch")
}
clientProof := make([]byte, len(clientKey))
for i := range clientKey {
clientProof[i] = clientKey[i] ^ clientSignature[i]
}
h = hmac.New(shaNewFn, saltedPassword)
if _, err = h.Write([]byte("Server Key")); err != nil {
return err
}
serverKey := h.Sum(nil)
h.Reset()
h = hmac.New(shaNewFn, serverKey)
if _, err = h.Write([]byte(authMessage)); err != nil {
return err
}
serverSignature = h.Sum(nil)
if string(serverSignature) == "" {
return errors.New("SCRAM: calculated an empty server signature")
}
clientFinalMessage := base64.StdEncoding.EncodeToString(
[]byte(
clientFinalMessageBare + ",p=" + base64.StdEncoding.EncodeToString(clientProof),
),
)
_, err = fmt.Fprintf(
StanzaWriter,
"<response xmlns='%s'>%s</response>",
nsSASL,
clientFinalMessage,
)
if err != nil {
return err
}
}
if mechanism == "X-OAUTH2" && o.OAuthToken != "" && o.OAuthScope != "" {
// Oauth authentication is very similar to PLAIN: we send base64-encoded \x00 user \x00 token.
raw := "\x00" + user + "\x00" + o.OAuthToken
enc := make([]byte, base64.StdEncoding.EncodedLen(len(raw)))
base64.StdEncoding.Encode(enc, []byte(raw))
_, err := fmt.Fprintf(StanzaWriter, "<auth xmlns='%s' mechanism='X-OAUTH2' auth:service='oauth2' "+
"xmlns:auth='%s'>%s</auth>\n", nsSASL, o.OAuthXmlNs, enc)
if err != nil {
return err
}
}
if mechanism == "PLAIN" {
// Plain authentication: according to rfc4616, it is sufficient to send base64-encoded
// \x00 user \x00 password.
var (
raw []byte
enc []byte
)
raw = append(raw, []byte("\x00")...)
raw = append(raw, []byte(user)...)
raw = append(raw, []byte("\x00")...)
raw = append(raw, []byte(o.Password)...)
base64.StdEncoding.Encode(enc, raw)
_, err := fmt.Fprintf(c.conn, "<auth xmlns='%s' mechanism='PLAIN'>%s</auth>\n", nsSASL, enc)
if err != nil {
return err
}
}
if mechanism == "DIGEST-MD5" {
// Digest-MD5 authentication
// Step one, https://datatracker.ietf.org/doc/html/rfc2831#section-2.1.1
_, err := fmt.Fprintf(StanzaWriter, "<auth xmlns='%s' mechanism='DIGEST-MD5'/>\n", nsSASL)
if err != nil {
return err
}
var ch saslChallenge
if err = c.p.DecodeElement(&ch, nil); err != nil {
return errors.New("unmarshal <challenge>: " + err.Error())
}
b, err := base64.StdEncoding.DecodeString(string(ch))
if err != nil {
return err
}
tokens := map[string]string{}
for _, token := range strings.Split(string(b), ",") {
kv := strings.SplitN(strings.TrimSpace(token), "=", 2)
if len(kv) == 2 {
if kv[1][0] == '"' && kv[1][len(kv[1])-1] == '"' {
kv[1] = kv[1][1 : len(kv[1])-1]
}
tokens[kv[0]] = kv[1]
}
}
// Step two, https://datatracker.ietf.org/doc/html/rfc2831#section-2.1.2
var (
realm = tokens["realm"]
nonce = tokens["nonce"]
qop = tokens["qop"]
charset = tokens["charset"]
cnonceStr = cnonce()
digestURI = "xmpp/" + domain
nonceCount = fmt.Sprintf("%08x", 1)
)
// 2.1.2 part of rfc2831 says about charset:
// This directive, if present, specifies that the client has use UTF-8 encoding for the username
// and password. If not present, the username and password must be encoded in ISO 8859-1 (of which
// US-ASCII is a subset). The client should send this directive only if the server has indicated it
// supports UTF-8.
// So we have to somehow detect that server can do utf-8. Simplest way to check charset that we get in Step
// one.
var (
digest string
message []byte
)
if match, _ := regexp.MatchString("(UTF-8|UTF8|utf-8|utf8)", charset); match {
digest = saslDigestResponse(user, realm, o.Password, nonce, cnonceStr, "AUTHENTICATE",
digestURI, nonceCount)
} else {
encoder := charmap.ISO8859_1.NewEncoder()
password, err := encoder.Bytes([]byte(o.Password))
if err != nil {
return err
}
digest = saslDigestResponse(user, realm, string(password), nonce, cnonceStr, "AUTHENTICATE",
digestURI, nonceCount)
}
if match, _ := regexp.MatchString("(UTF-8|UTF8|utf-8|utf8)", charset); match {
message = append(message, []byte(`username="`)...)
message = append(message, []byte(user)...)
message = append(message, []byte(`", "`)...)
} else {
encoder := charmap.ISO8859_1.NewEncoder()
userISO, err := encoder.Bytes([]byte(user))
if err != nil {
return err
}
message = append(message, []byte(`username="`)...)
message = append(message, userISO...)
message = append(message, []byte(`", "`)...)
}
message = append(message, []byte(fmt.Sprintf(`realm="%s", `, realm))...)
message = append(message, []byte(fmt.Sprintf(`nonce="%s", `, nonce))...)
message = append(message, []byte(fmt.Sprintf(`cnonce="%s", `, cnonceStr))...)
message = append(message, []byte(fmt.Sprintf(`nc="%s", `, nonceCount))...)
message = append(message, []byte(fmt.Sprintf(`qop="%s", `, qop))...)
message = append(message, []byte(fmt.Sprintf(`digest-uri="%s", `, digestURI))...)
message = append(message, []byte(fmt.Sprintf(`response="%s", `, digest))...)
if match, _ := regexp.MatchString("^(UTF-8|UTF8|utf-8|utf8)$", charset); match {
message = append(message, []byte(`username="`)...)
message = append(message, []byte(charset)...)
message = append(message, []byte(`", "`)...)
}
_, err = fmt.Fprintf(
StanzaWriter,
"<response xmlns='%s'>%s</response>\n",
nsSASL,
base64.StdEncoding.EncodeToString(message),
)
if err != nil {
return err
}
// Step three, server checks if we supplied correct response
var rspauth saslRspAuth
// TODO: more accurate decode responses, taking into account tag names.
// In this case success is something like
// <challenge xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>cnNwYXV0aD1lYTQwZjYwMzM1YzQyN2I1NTI3Yjg0ZGJhYmNkZmZmZA==</challenge>
// while fail is something like this:
// <response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>
if err = c.p.DecodeElement(&rspauth, nil); err != nil {
return errors.New("unmarshal <challenge>: " + err.Error())
}
b, err = base64.StdEncoding.DecodeString(string(rspauth))
if err != nil {
return err
}
// Empty b we should understand it as auth error.
if len(b) == 0 {
return errors.New("auth failure: server answer with empty response, looks like incorrect login or password")
}
// Step four, answer with empty response
_, err = fmt.Fprintf(StanzaWriter, "<response xmlns='%s'/>\n", nsSASL)
if err != nil {
return err
}
}
}
if mechanism == "" {
return fmt.Errorf("PLAIN authentication is not an option: %v", f.Mechanisms.Mechanism)
}
// Next message should be either success or failure.
name, val, err := next(c.p)
if err != nil {
return err
}
switch v := val.(type) {
case *saslSuccess:
if strings.HasPrefix(mechanism, "SCRAM-SHA") {
successMsg, err := base64.StdEncoding.DecodeString(v.Text)
if err != nil {
return err
}
if !strings.HasPrefix(string(successMsg), "v=") {
return errors.New("server sent unexpected content in SCRAM success message")
}
serverSignatureReply := strings.SplitN(string(successMsg), "v=", 2)[1]
serverSignatureRemote, err := base64.StdEncoding.DecodeString(serverSignatureReply)
if err != nil {
return err
}
if string(serverSignature) != string(serverSignatureRemote) {
return errors.New("SCRAM: server signature mismatch")
}
}
case *saslFailure:
errorMessage := v.Text
if errorMessage == "" {
// v.Any is type of sub-element in failure,
// which gives a description of what failed if there was no text element
errorMessage = v.Any.Local
}
return errors.New("auth failure: " + errorMessage)
default:
return errors.New("expected <success> or <failure>, got <" + name.Local + "> in " + name.Space)
}
// Now that we're authenticated, we're supposed to start the stream over again.
// Declare intent to be a jabber client.
// TODO: check if we can squeeze something useful of f (aka server features)
if f, err = c.startStream(o, domain); err != nil {
return err
}
// Generate a unique cookie
cookie := getCookie()
// Send IQ message asking to bind to the local user name.
if o.Resource == "" {
_, err = fmt.Fprintf(StanzaWriter, "<iq type='set' id='%x'><bind xmlns='%s'></bind></iq>\n", cookie, nsBind)
if err != nil {
return err
}
} else {
_, err = fmt.Fprintf(StanzaWriter, "<iq type='set' id='%x'><bind xmlns='%s'><resource>%s</resource></bind></iq>\n", cookie, nsBind, o.Resource)
if err != nil {
return err
}
}
var iq clientIQ
if err = c.p.DecodeElement(&iq, nil); err != nil {
return errors.New("unmarshal <iq>: " + err.Error())
}
if (iq.Bind == bindBind{}) {
return errors.New("<iq> result missing <bind>")
}
c.jid = iq.Bind.Jid // our local id
c.domain = domain
if o.Session {
// if server support session, open it
_, err = fmt.Fprintf(StanzaWriter, "<iq to='%s' type='set' id='%x'><session xmlns='%s'/></iq>", xmlEscape(domain), cookie, nsSession)
if err != nil {
return err
}
}
// We're connected and can now receive and send messages.
_, err = fmt.Fprintf(StanzaWriter, "<presence xml:lang='en'><show>%s</show><status>%s</status></presence>", o.Status, o.StatusMessage)
if err != nil {
return err
}
return nil
}
// startTlsIfRequired examines the server's stream features and, if STARTTLS is required or supported, performs the TLS handshake.
// f will be updated if the handshake completes, as the new stream's features are typically different from the original.
func (c *Client) startTLSIfRequired(f *streamFeatures, o *Options, domain string) (*streamFeatures, error) {
// whether we start tls is a matter of opinion: the server's and the user's.
switch {
case f.StartTLS == nil:
// the server does not support STARTTLS
return f, nil
case !o.StartTLS && f.StartTLS.Required == nil:
return f, nil
case f.StartTLS.Required != nil:
// the server requires STARTTLS.
case !o.StartTLS:
// the user wants STARTTLS and the server supports it.
} //nolint:wsl
var err error
_, err = fmt.Fprintf(StanzaWriter, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>\n")
if err != nil {
return f, err
}
var k tlsProceed
if err = c.p.DecodeElement(&k, nil); err != nil {
return f, errors.New("unmarshal <proceed>: " + err.Error())
}
tc := o.TLSConfig
if tc == nil {
tc = DefaultConfig.Clone()
// TODO(scott): we should consider using the server's address or reverse lookup
tc.ServerName = domain
}
t := tls.Client(c.conn, tc)
if err = t.Handshake(); err != nil {
return f, errors.New("starttls handshake: " + err.Error())
}
c.conn = t