154 lines
5.4 KiB
Go
154 lines
5.4 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"crypto/tls"
|
|
"errors"
|
|
"fmt"
|
|
"net"
|
|
"net/mail"
|
|
"net/smtp"
|
|
"net/url"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"pageswiki/internal/store"
|
|
)
|
|
|
|
const smtpDeliveryTimeout = 10 * time.Second
|
|
|
|
type smtpLimitedConn struct {
|
|
net.Conn
|
|
remaining int
|
|
}
|
|
|
|
func (c *smtpLimitedConn) Read(buffer []byte) (int, error) {
|
|
if c.remaining <= 0 {
|
|
return 0, errors.New("SMTP response exceeds the size limit")
|
|
}
|
|
if len(buffer) > c.remaining {
|
|
buffer = buffer[:c.remaining]
|
|
}
|
|
n, err := c.Conn.Read(buffer)
|
|
c.remaining -= n
|
|
return n, err
|
|
}
|
|
|
|
type magicLinkChallenge struct {
|
|
Return string `json:"return"`
|
|
Email string `json:"email"`
|
|
Remember bool `json:"remember,omitempty"`
|
|
}
|
|
|
|
func smtpMailbox(value string) (*mail.Address, error) {
|
|
if len(value) == 0 || len(value) > 512 || strings.ContainsAny(value, "\r\n\x00") {
|
|
return nil, errors.New("invalid mail address")
|
|
}
|
|
address, err := mail.ParseAddress(value)
|
|
if err != nil || !strings.Contains(address.Address, "@") || strings.ContainsAny(address.Address, "\r\n\x00") {
|
|
return nil, errors.New("invalid mail address")
|
|
}
|
|
return address, nil
|
|
}
|
|
|
|
func smtpMessage(config store.AuthProviderConfig, recipient, link string) (host, from, to string, message []byte, err error) {
|
|
fail := func() (string, string, string, []byte, error) {
|
|
return "", "", "", nil, errors.New("invalid SMTP configuration or message")
|
|
}
|
|
if len(config.SMTPAddress) > 1024 || strings.ContainsAny(config.SMTPAddress, "\r\n\x00 /@") {
|
|
return fail()
|
|
}
|
|
host, port, parseErr := net.SplitHostPort(config.SMTPAddress)
|
|
portNumber, portErr := strconv.Atoi(port)
|
|
if parseErr != nil || portErr != nil || host == "" || portNumber < 1 || portNumber > 65535 || len(config.SMTPUsername) > 1024 || len(config.SMTPPassword) > 4096 {
|
|
return fail()
|
|
}
|
|
sender, senderErr := smtpMailbox(config.SMTPFrom)
|
|
addressee, recipientErr := smtpMailbox(recipient)
|
|
parsedLink, linkErr := url.Parse(link)
|
|
if senderErr != nil || recipientErr != nil || linkErr != nil || len(link) > 4096 || strings.ContainsAny(link, "\r\n\x00") || parsedLink.Hostname() == "" || parsedLink.User != nil || parsedLink.Fragment != "" || (parsedLink.Scheme != "http" && parsedLink.Scheme != "https") {
|
|
return fail()
|
|
}
|
|
message = []byte(fmt.Sprintf("To: %s\r\nFrom: %s\r\nSubject: Pages Wiki sign-in link\r\nDate: %s\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\n%s\r\n", addressee.String(), sender.String(), time.Now().Format(time.RFC1123Z), link))
|
|
return host, sender.Address, addressee.Address, message, nil
|
|
}
|
|
|
|
// sendMagicLinkSMTP bounds greeting, EHLO, TLS, AUTH, DATA, and QUIT as well as
|
|
// dial time. No provider response, recipient, credential, or login URL is logged.
|
|
func sendMagicLinkSMTP(ctx context.Context, config store.AuthProviderConfig, recipient, link string) error {
|
|
return sendMagicLinkSMTPWithTLS(ctx, config, recipient, link, nil)
|
|
}
|
|
|
|
func sendMagicLinkSMTPWithTLS(ctx context.Context, config store.AuthProviderConfig, recipient, link string, tlsOverride *tls.Config) error {
|
|
host, sender, addressee, message, err := smtpMessage(config, recipient, link)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return deliverSMTPMessage(ctx, config, host, sender, addressee, message, tlsOverride)
|
|
}
|
|
|
|
func deliverSMTPMessage(ctx context.Context, config store.AuthProviderConfig, host, sender, addressee string, message []byte, tlsOverride *tls.Config) error {
|
|
ctx, cancel := context.WithTimeout(ctx, smtpDeliveryTimeout)
|
|
defer cancel()
|
|
connection, err := (&net.Dialer{Timeout: 3 * time.Second}).DialContext(ctx, "tcp", config.SMTPAddress)
|
|
if err != nil {
|
|
return errors.New("SMTP connection failed")
|
|
}
|
|
connection = &smtpLimitedConn{Conn: connection, remaining: 256 << 10}
|
|
defer connection.Close()
|
|
deadline, _ := ctx.Deadline()
|
|
if err := connection.SetDeadline(deadline); err != nil {
|
|
return errors.New("SMTP connection deadline failed")
|
|
}
|
|
stop := context.AfterFunc(ctx, func() { _ = connection.Close() })
|
|
defer stop()
|
|
client, err := smtp.NewClient(connection, host)
|
|
if err != nil {
|
|
return errors.New("SMTP greeting failed")
|
|
}
|
|
defer client.Close()
|
|
if err := client.Hello("localhost"); err != nil {
|
|
return errors.New("SMTP greeting failed")
|
|
}
|
|
if available, _ := client.Extension("STARTTLS"); available {
|
|
config := &tls.Config{ServerName: host, MinVersion: tls.VersionTLS12}
|
|
if tlsOverride != nil {
|
|
config = tlsOverride.Clone()
|
|
config.ServerName = host
|
|
config.MinVersion = max(config.MinVersion, tls.VersionTLS12)
|
|
}
|
|
if err := client.StartTLS(config); err != nil {
|
|
return errors.New("SMTP TLS negotiation failed")
|
|
}
|
|
}
|
|
if config.SMTPUsername != "" {
|
|
if _, secure := client.TLSConnectionState(); !secure {
|
|
return errors.New("SMTP authentication requires TLS")
|
|
}
|
|
if err := client.Auth(smtp.PlainAuth("", config.SMTPUsername, config.SMTPPassword, host)); err != nil {
|
|
return errors.New("SMTP authentication failed")
|
|
}
|
|
}
|
|
if err := client.Mail(sender); err != nil {
|
|
return errors.New("SMTP sender rejected")
|
|
}
|
|
if err := client.Rcpt(addressee); err != nil {
|
|
return errors.New("SMTP recipient rejected")
|
|
}
|
|
writer, err := client.Data()
|
|
if err != nil {
|
|
return errors.New("SMTP data rejected")
|
|
}
|
|
if _, err := writer.Write(message); err != nil {
|
|
return errors.New("SMTP delivery failed")
|
|
}
|
|
if err := writer.Close(); err != nil {
|
|
return errors.New("SMTP delivery failed")
|
|
}
|
|
if err := client.Quit(); err != nil {
|
|
return errors.New("SMTP completion failed")
|
|
}
|
|
return nil
|
|
}
|