sasl.go 5.2 KB

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