Commit 668a7e08 authored by jan.koester's avatar jan.koester
Browse files

Registration: claim the link before creating the account, no control chars

- the mail link is claimed (mail_tokens primary key) before the fenrirds
  account is created, plus a short lock row per address: parallel requests
  with one link, or two links for one address, create only one account;
  released again when creating fails so the link can be retried
- step 2 checks again whether the address has an account (fenrirds + local),
  fail closed when fenrirds can't be asked
- first/last name: control characters refused; adminPost refuses CR/LF/NUL
  and the boundary in multipart fields

Co-Authored-By: default avatarClaude Opus 5.5 <noreply@anthropic.com>
parent afdda56c
Loading
Loading
Loading
Loading
+5
Changes for share/i18n/en.tsv: 5 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -456,3 +456,8 @@ Setup-Code Setup code
Öffentliche Adresse	Public address
z.B. https://forum.example.org -- für die Links in E-Mails; leer = https:// und der aufgerufene Domainname	e.g. https://forum.example.org -- for the links in mails; empty = https:// and the requested domain name
Die öffentliche Adresse muss http(s)://host[:port] sein (ohne Pfad).	The public address must be http(s)://host[:port] (without a path).
Vor- und Nachname dürfen keine Steuerzeichen enthalten.	First and last name must not contain control characters.
Für diese Adresse läuft gerade schon eine Registrierung. Bitte versuche es gleich noch einmal.	A registration for this address is already in progress. Please try again in a moment.
Es gibt schon ein Konto mit dieser Adresse. Melde dich damit an.	There is already an account with this address. Please log in with it.
Der Verzeichnisdienst ist nicht erreichbar.	The directory service is not reachable.
Die Registrierung ist gerade nicht möglich.	Registration is not possible right now.
+8 −2
Changes for src/auth.cpp: 8 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -495,6 +495,12 @@ namespace {
                              const std::string &fileField = "", const std::vector<char> &file = {}) const {
            std::string boundary = "----florium" + florium::randomToken(12);
            std::string body;
            // values come from sign up forms: no line breaks/NULs (no smuggled parts or headers)
            for (const auto &[name, value] : fields)
                for (const std::string *s : {&name, &value})
                    if (s->find_first_of(std::string("\r\n\0", 3)) != std::string::npos ||
                        s->find(boundary) != std::string::npos)
                        throw std::invalid_argument("control character in field " + name);
            for (const auto &[name, value] : fields)
                body += "--" + boundary + "\r\nContent-Disposition: form-data; name=\"" + name + "\"\r\n\r\n" + value +
                        "\r\n";
@@ -611,11 +617,11 @@ namespace {
                setup(con);
                fenrirds::client::Client clt(con);
                if (!clt.ClientAuth())
                    return false;
                    throw std::runtime_error("client login failed");
                return clt.lookupUser(mail).found;
            } catch (const std::exception &e) {
                std::cerr << "florium: fenrirds lookupUser: " << e.what() << "\n";
                return false;
                throw;
            }
        }

+4 −1
Changes for src/auth.h: 4 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -100,7 +100,10 @@ namespace florium {

        virtual bool canRegister() const = 0;
        virtual bool registerUser(const Registration &reg, std::string &error) = 0;
        /** An account with this mail address exists already (registration sends a hint instead). */
        /**
         * An account with this mail address exists already (registration sends a hint instead).
         * Throws when the directory cannot be asked.
         */
        virtual bool mailInUse(const std::string &mail) = 0;

        /** The directory's picture of the account (fenrirds getavatar). */
+57 −3
Changes for src/ucp.cpp: 57 added lines, 3 removed lines.
Original line number Diff line number Diff line
@@ -613,6 +613,13 @@ namespace {
        return true;
    }

    bool hasControlChars(const std::string &s) {
        for (unsigned char c : s)
            if (c < 0x20 || c == 0x7f)
                return true;
        return false;
    }

    std::string lowerStr(std::string s) {
        for (char &c : s)
            c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
@@ -679,7 +686,13 @@ void Forum::registerUser(Request &r) {
            cur().registerLimiter.hit("mail:" + lowerStr(mail));
            const std::string &title = cur().cfg.title;
            std::string subject, text;
            if (cur().dir->mailInUse(mail)) {
            bool inUse = false;
            try {
                inUse = cur().dir->mailInUse(mail);
            } catch (const std::exception &) {
                // send the link anyway: step 2 checks again and refuses while the directory is down
            }
            if (inUse) {
                subject = en ? "Your account at " + title : "Dein Konto bei " + title;
                text = en ? "Hello,\n\nsomeone (probably you) wanted to register at " + title +
                                " with this address, but an account with this address exists already.\n\n"
@@ -769,12 +782,53 @@ void Forum::registerAccount(Request &r, const std::string &token) {
            error = loc("Die Passwörter stimmen nicht überein.");
        else if (utf8Length(first) > 64 || utf8Length(last) > 64)
            error = loc("Vor- oder Nachname ist zu lang.");
        else if (hasControlChars(first) || hasControlChars(last))
            error = loc("Vor- und Nachname dürfen keine Steuerzeichen enthalten.");
        else if (r.arg("rules") != "yes")
            error = loc("Bitte bestätige die Forenregeln.");
        else {
            // Claim the link before the account is created: two parallel requests with the same
            // link can't both get through (primary key). A second lock row per address stops
            // two different links for the same address from racing each other.
            std::string mailLock = sha256Hex("mail|" + lowerStr(mail));
            try {
                r.db.exec("INSERT INTO mail_tokens (hash) VALUES (" + Db::q(tokenHash) + ")");
            } catch (const std::exception &) {
                throw HttpError{400, loc("Dieser Link wurde schon benutzt. Melde dich mit deinem Konto an.")};
            }
            r.db.exec("DELETE FROM mail_tokens WHERE hash = " + Db::q(mailLock) + " AND used < now() - INTERVAL '10 minutes'");
            bool locked = false;
            try {
                r.db.exec("INSERT INTO mail_tokens (hash) VALUES (" + Db::q(mailLock) + ")");
                locked = true;
            } catch (const std::exception &) {
                error = loc("Für diese Adresse läuft gerade schon eine Registrierung. Bitte versuche es gleich noch einmal.");
            }
            bool created = false;
            if (locked) {
                bool inUse = true;
                try {
                    inUse = cur().dir->mailInUse(mail) ||
                            !r.db.scalar("SELECT id FROM users WHERE lower(email) = " + Db::q(lowerStr(mail))).empty();
                    if (inUse)
                        error = loc("Es gibt schon ein Konto mit dieser Adresse. Melde dich damit an.");
                } catch (const std::exception &) {
                    error = loc("Der Verzeichnisdienst ist nicht erreichbar.");
                }
                if (!inUse) {
                    Registration reg{username, pw, mail, first, last};
            if (cur().dir->registerUser(reg, error)) {
                r.db.exec("INSERT INTO mail_tokens (hash) VALUES (" + Db::q(tokenHash) + ") ON CONFLICT (hash) DO NOTHING");
                    try {
                        created = cur().dir->registerUser(reg, error);
                    } catch (const std::exception &e) {
                        std::cerr << "florium: register " << username << ": " << e.what() << "\n";
                        error = loc("Die Registrierung ist gerade nicht möglich.");
                    }
                }
                r.db.exec("DELETE FROM mail_tokens WHERE hash = " + Db::q(mailLock));
            }
            if (!created)   // the link stays usable for another try (other user name, directory back)
                r.db.exec("DELETE FROM mail_tokens WHERE hash = " + Db::q(tokenHash));
            if (created) {
                std::cerr << "florium: " << cur().cfg.label() << ": registered " << username << " <" << mail << ">\n";
                Identity id;
                std::string lerr;
+12
Changes for test/e2e.sh: 12 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -193,6 +193,18 @@ r=$(get dup "/register?token=$T2")
r=$(post dup /register --data-urlencode "token=$T2" --data-urlencode username=newbie \
     --data-urlencode password=geheim123 --data-urlencode password2=geheim123 --data-urlencode rules=yes)
check "$TMP/out" "schon vergeben" "duplicate username"
r=$(post dup /register --data-urlencode "token=$T2" --data-urlencode username=dupuser --data-urlencode "firstname=$(printf 'A\r\nmail')" \
     --data-urlencode password=geheim123 --data-urlencode password2=geheim123 --data-urlencode rules=yes)
check "$TMP/out" "Steuerzeichen" "line break in first name refused"
# the same link twice at the same time: only one account
cp "$TMP/dup" "$TMP/dup2"
for n in a b c; do
  curl -s -b "$TMP/dup" -o "$TMP/race$n" -w "%{redirect_url}" --data-urlencode "csrf=$(csrf dup)" --data-urlencode "token=$T2" \
       --data-urlencode "username=racer$n" --data-urlencode password=geheim123 --data-urlencode password2=geheim123 \
       --data-urlencode rules=yes "$BASE/register" > "$TMP/race$n.url" &
done
wait
[ "$(cat "$TMP"/race?.url | grep -o 'welcome=1' | wc -l)" = 1 ] && ok || bad "parallel use of one link: $(cat "$TMP"/race?.url)"

# ---- per forum fenrirds policies ----------------------------------------------------------
r=$(post admin /admin --data-urlencode action=forum_add --data-urlencode "title=Team intern" --data-urlencode "category=$CAT" \