sasl.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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. "git.semlanik.org/semlanik/gostfix/auth"
  40. "github.com/google/uuid"
  41. )
  42. type SaslServer struct {
  43. pid int
  44. cuid int
  45. authenticator *auth.Authenticator
  46. }
  47. const (
  48. Version = "VERSION"
  49. CPid = "CPID"
  50. SPid = "SPID"
  51. Cuid = "CUID"
  52. Cookie = "COOKIE"
  53. Mech = "MECH"
  54. Done = "DONE"
  55. Auth = "AUTH"
  56. Fail = "FAIL"
  57. Cont = "CONT"
  58. Ok = "OK"
  59. )
  60. const (
  61. ContinueStateNone = iota
  62. ContinueStateCredentials
  63. )
  64. func NewSaslServer() (*SaslServer, error) {
  65. authenticator, err := auth.NewAuthenticator()
  66. if err != nil {
  67. return nil, err
  68. }
  69. return &SaslServer{
  70. pid: os.Getpid(),
  71. cuid: 0,
  72. authenticator: authenticator,
  73. }, nil
  74. }
  75. func (s *SaslServer) Run() {
  76. go func() {
  77. l, err := net.Listen("tcp", "127.0.0.1:65201")
  78. if err != nil {
  79. log.Fatalf("Coulf not start SASL server: %s\n", err)
  80. return
  81. }
  82. defer l.Close()
  83. log.Printf("Listen sasl on: %s\n", l.Addr().String())
  84. for {
  85. conn, err := l.Accept()
  86. s.cuid++
  87. if err != nil {
  88. log.Println("Error accepting: ", err.Error())
  89. continue
  90. }
  91. go s.handleRequest(conn)
  92. }
  93. }()
  94. }
  95. func (s *SaslServer) handleRequest(conn net.Conn) {
  96. connectionReader := bufio.NewReader(conn)
  97. continueState := ContinueStateNone
  98. for {
  99. fullbuf, err := connectionReader.ReadString('\n')
  100. if err == io.EOF {
  101. break
  102. }
  103. if err != nil {
  104. log.Printf("Read error %s\n", err)
  105. break
  106. }
  107. currentMessage := fullbuf
  108. ids := strings.Split(currentMessage, "\t")
  109. if len(ids) < 2 {
  110. break
  111. }
  112. switch ids[0] {
  113. case Version:
  114. if len(ids) < 3 {
  115. break
  116. }
  117. if major, err := strconv.Atoi(ids[1]); err != nil || major != 1 {
  118. break
  119. }
  120. cookieUuid := uuid.New()
  121. fmt.Fprintf(conn, "%s\t%d\t%d\n", Version, 1, 2)
  122. fmt.Fprintf(conn, "%s\t%s\t%s\n", Mech, "PLAIN", "plaintext")
  123. fmt.Fprintf(conn, "%s\t%s\t%s\n", Mech, "LOGIN", "plaintext")
  124. fmt.Fprintf(conn, "%s\t%d\n", SPid, s.pid)
  125. fmt.Fprintf(conn, "%s\t%d\n", Cuid, s.cuid)
  126. fmt.Fprintf(conn, "%s\t%s\n", Cookie, hex.EncodeToString(cookieUuid[:]))
  127. fmt.Fprintf(conn, "%s\n", Done)
  128. case Auth:
  129. for _, authId := range ids {
  130. if strings.Index(authId, "resp=") == 0 {
  131. login, err := s.checkCredentials(authId[5:])
  132. if err != nil {
  133. fmt.Fprintf(conn, "%s\t%s\treason=%s\n", Fail, ids[1], err.Error())
  134. } else {
  135. fmt.Fprintf(conn, "%s\t%s\tuser=%s\n", Ok, ids[1], login)
  136. }
  137. continueState = ContinueStateNone
  138. return
  139. }
  140. }
  141. fmt.Fprintf(conn, "%s\t%s\t%s\n", Cont, ids[1], base64.StdEncoding.EncodeToString([]byte("Username:")))
  142. continueState = ContinueStateCredentials
  143. case Cont:
  144. if len(ids) < 2 {
  145. break
  146. }
  147. if continueState == ContinueStateCredentials {
  148. if len(ids) < 3 {
  149. fmt.Fprintf(conn, "%s\t%s\treason=%s\n", Fail, ids[1], "invalid base64 data")
  150. return
  151. }
  152. login, err := s.checkCredentials(ids[2])
  153. if err != nil {
  154. fmt.Fprintf(conn, "%s\t%s\treason=%s\n", Fail, ids[1], err.Error())
  155. } else {
  156. fmt.Fprintf(conn, "%s\t%s\tuser=%s\n", Ok, ids[1], login)
  157. }
  158. continueState = ContinueStateNone
  159. } else {
  160. fmt.Fprintf(conn, "%s\t%s\treason=%s\n", Fail, ids[1], "invalid user or password")
  161. }
  162. }
  163. }
  164. conn.Close()
  165. }
  166. func (s *SaslServer) checkCredentials(credentialsBase64 string) (string, error) {
  167. credentials, err := base64.StdEncoding.DecodeString(credentialsBase64)
  168. if err != nil {
  169. return "", errors.New("invalid base64 data")
  170. }
  171. credentialList := bytes.Split(credentials, []byte{0})
  172. if len(credentialList) < 3 {
  173. return "", errors.New("invalid user or password")
  174. }
  175. identity := string(credentialList[0])
  176. login := string(credentialList[1])
  177. password := string(credentialList[2])
  178. if identity == "token" {
  179. if s.authenticator.Verify(login, password) {
  180. return login, nil
  181. }
  182. } else {
  183. if err := s.authenticator.CheckUser(login, password); err == nil {
  184. return login, nil
  185. }
  186. }
  187. return "", errors.New("invalid user or password")
  188. }