sasl.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. /*
  2. * MIT License
  3. *
  4. * Copyright (c) 2020 Alexey Edelev <semlanik@gmail.com>
  5. *
  6. * This file is part of gostfix project https://git.semlanik.org/semlanik/gostfix
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy of this
  9. * software and associated documentation files (the "Software"), to deal in the Software
  10. * without restriction, including without limitation the rights to use, copy, modify,
  11. * merge, publish, distribute, sublicense, and/or sell copies of the Software, and
  12. * to permit persons to whom the Software is furnished to do so, subject to the following
  13. * conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all copies
  16. * or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  19. * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  20. * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
  21. * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  22. * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  23. * DEALINGS IN THE SOFTWARE.
  24. */
  25. package sasl
  26. import (
  27. "bufio"
  28. "bytes"
  29. "encoding/base64"
  30. "encoding/hex"
  31. "errors"
  32. "fmt"
  33. "io"
  34. "log"
  35. "net"
  36. "os"
  37. "strconv"
  38. "strings"
  39. "time"
  40. "git.semlanik.org/semlanik/gostfix/auth"
  41. "github.com/google/uuid"
  42. )
  43. type SaslServer struct {
  44. pid int
  45. cuid int
  46. authenticator *auth.Authenticator
  47. listener net.Listener
  48. }
  49. const (
  50. Version = "VERSION"
  51. CPid = "CPID"
  52. SPid = "SPID"
  53. Cuid = "CUID"
  54. Cookie = "COOKIE"
  55. Mech = "MECH"
  56. Done = "DONE"
  57. Auth = "AUTH"
  58. Fail = "FAIL"
  59. Cont = "CONT"
  60. Ok = "OK"
  61. )
  62. const (
  63. ContinueStateNone = iota
  64. ContinueStateCredentials
  65. )
  66. func NewSaslServer() (*SaslServer, error) {
  67. authenticator, err := auth.NewAuthenticator()
  68. if err != nil {
  69. return nil, err
  70. }
  71. return &SaslServer{
  72. pid: os.Getpid(),
  73. cuid: 0,
  74. authenticator: authenticator,
  75. }, nil
  76. }
  77. func (s *SaslServer) handleRequest(conn net.Conn) {
  78. conn.SetReadDeadline(time.Time{})
  79. defer conn.Close()
  80. connectionReader := bufio.NewReader(conn)
  81. continueState := ContinueStateNone
  82. for {
  83. fullbuf, err := connectionReader.ReadString('\n')
  84. if err == io.EOF {
  85. break
  86. }
  87. if err != nil {
  88. log.Printf("Read error %s\n", err)
  89. break
  90. }
  91. currentMessage := fullbuf
  92. ids := strings.Split(currentMessage, "\t")
  93. if len(ids) < 2 {
  94. break
  95. }
  96. switch ids[0] {
  97. case Version:
  98. if len(ids) < 3 {
  99. break
  100. }
  101. if major, err := strconv.Atoi(ids[1]); err != nil || major != 1 {
  102. break
  103. }
  104. cookieUuid := uuid.New()
  105. fmt.Fprintf(conn, "%s\t%d\t%d\n", Version, 1, 2)
  106. fmt.Fprintf(conn, "%s\t%s\t%s\n", Mech, "PLAIN", "plaintext")
  107. fmt.Fprintf(conn, "%s\t%s\t%s\n", Mech, "LOGIN", "plaintext")
  108. fmt.Fprintf(conn, "%s\t%d\n", SPid, s.pid)
  109. fmt.Fprintf(conn, "%s\t%d\n", Cuid, s.cuid)
  110. fmt.Fprintf(conn, "%s\t%s\n", Cookie, hex.EncodeToString(cookieUuid[:]))
  111. fmt.Fprintf(conn, "%s\n", Done)
  112. case Auth:
  113. for _, authId := range ids {
  114. if strings.Index(authId, "resp=") == 0 {
  115. login, err := s.checkCredentials(authId[5:])
  116. if err != nil {
  117. fmt.Fprintf(conn, "%s\t%s\treason=%s\n", Fail, ids[1], err.Error())
  118. } else {
  119. fmt.Fprintf(conn, "%s\t%s\tuser=%s\n", Ok, ids[1], login)
  120. }
  121. continueState = ContinueStateNone
  122. continue
  123. }
  124. }
  125. fmt.Fprintf(conn, "%s\t%s\t%s\n", Cont, ids[1], base64.StdEncoding.EncodeToString([]byte("Username:")))
  126. continueState = ContinueStateCredentials
  127. case Cont:
  128. if len(ids) < 2 {
  129. break
  130. }
  131. if continueState == ContinueStateCredentials {
  132. if len(ids) < 3 {
  133. fmt.Fprintf(conn, "%s\t%s\treason=%s\n", Fail, ids[1], "invalid base64 data")
  134. return
  135. }
  136. login, err := s.checkCredentials(ids[2])
  137. if err != nil {
  138. fmt.Fprintf(conn, "%s\t%s\treason=%s\n", Fail, ids[1], err.Error())
  139. } else {
  140. fmt.Fprintf(conn, "%s\t%s\tuser=%s\n", Ok, ids[1], login)
  141. }
  142. continueState = ContinueStateNone
  143. } else {
  144. fmt.Fprintf(conn, "%s\t%s\treason=%s\n", Fail, ids[1], "invalid user or password")
  145. }
  146. }
  147. }
  148. }
  149. func (s *SaslServer) checkCredentials(credentialsBase64 string) (string, error) {
  150. credentials, err := base64.StdEncoding.DecodeString(credentialsBase64)
  151. if err != nil {
  152. return "", errors.New("invalid base64 data")
  153. }
  154. credentialList := bytes.Split(credentials, []byte{0})
  155. if len(credentialList) < 3 {
  156. return "", errors.New("invalid user or password")
  157. }
  158. identity := string(credentialList[0])
  159. login := string(credentialList[1])
  160. password := string(credentialList[2])
  161. if identity == "token" {
  162. if s.authenticator.Verify(login, password) {
  163. return login, nil
  164. }
  165. } else {
  166. if err := s.authenticator.CheckUser(login, password); err == nil {
  167. return login, nil
  168. }
  169. }
  170. return "", errors.New("invalid user or password")
  171. }