<?xml version="1.0" encoding="UTF-8"?>
<rfc xmlns:xi="http://www.w3.org/2001/XInclude"
     version="3"
     category="info"
     docName="draft-rigopoulos-totp-implementation-guidance-00"
     ipr="trust200902"
     submissionType="IETF"
     updates="6238"
     tocInclude="true"
     indexInclude="false"
     sortRefs="true"
     symRefs="true"
     xml:lang="en">
<front>
<title abbrev="Update to RFC 6238 (TOTP)">Update to the Time-Based One-Time Password Algorithm (TOTP): One-Time Use of an OTP</title>
<seriesInfo name="Internet-Draft" value="draft-rigopoulos-totp-implementation-guidance-00"/>
<author fullname="E. A. Rigopoulos" initials="E. A." surname="Rigopoulos">
<address><email>ea.rigopoulos@ypsservices.com</email></address>
</author>
<date day="6" month="December" year="2026"/>
<area>Security</area>
<keyword>TOTP</keyword>
<keyword>HOTP</keyword>
<keyword>one-time use</keyword>
<abstract>
<t>Section 5.2 of RFC 6238 requires that the verifier not accept the second attempt of an OTP after a successful validation, and leaves the method to the implementer.  This document updates and extends RFC 6238 with a stored last accepted time step and a single atomic check-and-store step, so that each OTP is accepted at most once.  It adds one recommendation on when an OTP is produced.  Nothing else changes.  Reference code and test results are included.</t>
</abstract>
</front>
<middle>
<section anchor="sec-1"><name>Introduction</name>
<t>Section 5.2 of <xref target="RFC6238"/> states that the verifier MUST NOT accept the second attempt of an OTP after the successful validation of the first, and leaves the method to the implementer.  This document updates and extends <xref target="RFC6238"/> with that method.  The transmission delay window, the time step size, and the OTP values do not change.  An OTP inside the window is accepted at most once.</t>
<t>For each point, the following lists what <xref target="RFC6238"/> says, the piece it does not specify, and the answer given here.</t>
<artwork type="text" name="" align="left"><![CDATA[
RFC 6238 says       Not specified          This document
------------------  ---------------------  ----------------------
R1: know Unix time  How exact it must be   Accurate source (Sec. 3)
No second attempt   What is kept           Last accepted time step
                                           (Sec. 5.2)
Same                Simultaneous attempts  One atomic step (Sec. 5.2)
Same                Several instances      One durable store
                                           (Sec. 5.2)
Resynchronization   Use with the rule      Advance the time step
                                           (Sec. 6)
The OTP value       When it is produced    Only on request (Sec. 4)
]]></artwork>
</section>
<section anchor="sec-2"><name>Notation and Terminology</name>
<t>The key words "<bcp14>MUST</bcp14>", "<bcp14>MUST NOT</bcp14>", "<bcp14>REQUIRED</bcp14>", "<bcp14>SHALL</bcp14>", "<bcp14>SHALL NOT</bcp14>", "<bcp14>SHOULD</bcp14>", "<bcp14>SHOULD NOT</bcp14>", "<bcp14>RECOMMENDED</bcp14>", "<bcp14>NOT RECOMMENDED</bcp14>", "<bcp14>MAY</bcp14>", and "<bcp14>OPTIONAL</bcp14>" in this document are to be interpreted as described in BCP 14 <xref target="RFC2119"/> <xref target="RFC8174"/> when, and only when, they appear in all capitals, as shown here.</t>
<t>The terms of Section 2 of <xref target="RFC6238"/> apply.  This document names the symbols of <xref target="RFC6238"/> once, here, and then uses words: the shared secret (K), the time step size (X), the Unix time to start counting time steps (T0), and the number of time steps (T) since that start time.</t>
<dl newline="false" spacing="normal" indent="3">
<dt>Last accepted time step:</dt><dd>The time step of the most recent OTP that the verifier has accepted for a prover.  The verifier keeps one for each prover.</dd>
</dl>
</section>
<section anchor="sec-3"><name>Algorithm Requirements</name>
<t>This section updates Section 3 of <xref target="RFC6238"/>.</t>
<t>Requirement R1 says that the prover and the verifier MUST know or be able to derive the current Unix time.  Unix time counts whole seconds since midnight UTC of January 1, 1970.  It is the same everywhere, has no time zones, and gives an exact number of time steps.  The verifier <bcp14>MUST</bcp14> obtain the current Unix time from an accurate time source, for example a network time source.</t>
</section>
<section anchor="sec-4"><name>TOTP Algorithm</name>
<t>This section updates Section 4 of <xref target="RFC6238"/>.</t>
<t>The algorithm, which uses HOTP <xref target="RFC4226"/>, and the OTP values are unchanged.  The prover and the verifier stay in step offline: each works out the same OTP from the shared secret and the current time step, with no contact between them.  Section 6 of <xref target="RFC6238"/> covers clock drift.</t>
<t>An application that displays an OTP <bcp14>SHOULD</bcp14> produce it only when the user asks for it, and <bcp14>SHOULD</bcp14> make it no longer available once it has been used or has expired.</t>
</section>
<section anchor="sec-5"><name>Security Considerations</name>
<section anchor="sec-5-1"><name>General</name>
<t>No change to Section 5.1 of <xref target="RFC6238"/>.</t>
</section>
<section anchor="sec-5-2"><name>Validation and Time-Step Size</name>
<t>This document updates Section 5.2 of <xref target="RFC6238"/> as follows.</t>
<artwork type="text" name="" align="left"><![CDATA[
=== OLD ===
Note that a prover may send the same OTP inside a given time-step
window multiple times to a verifier.  The verifier MUST NOT accept
the second attempt of the OTP after the successful validation has
been issued for the first OTP, which ensures one-time only use of an
OTP.

=== NEW ===
Note that a prover may send the same OTP inside a given time-step
window multiple times to a verifier.  The verifier MUST NOT accept
the second attempt of the OTP after the successful validation has
been issued for the first OTP, which ensures one-time only use of an
OTP.

To meet this requirement, the verifier MUST keep, for each prover,
the time step of the last OTP it accepted (the "last accepted time
step"), and MUST handle each received OTP as follows:

1.  Accept the OTP only if its time step is inside the transmission
    delay window and later than the last accepted time step.  If no
    time step has been accepted yet, any time step inside the window
    qualifies.

2.  Check and store in one atomic step: a single operation of the
    store that reports whether the value changed (for example a
    compare-and-swap).  If another attempt has already stored that
    time step or a later one, reject the OTP.

3.  Reject the OTP if the store cannot be reached.

4.  Keep the stored value across restarts and failover, and use the
    same store in every verifier instance for that prover.

The transmission delay window and the recommended time-step size of
30 seconds are unchanged.
=== END ===
]]></artwork>
<t>Rationale: <xref target="RFC6238"/> allows a window for transmission delay.  With the last accepted time step, an OTP inside that window is accepted at most once, including when two verifier instances receive it at the same moment.  A database update such as "UPDATE totp_state SET last_time_step = :time_step WHERE prover_id = :prover_id AND last_time_step &lt; :time_step" is a single operation of the kind that rule 2 describes.</t>
<t>Compatibility: a prover built to <xref target="RFC6238"/> works unchanged with a verifier built to this document.  Cost: one stored number for each prover, and one store operation for each accepted OTP.</t>
<t>An OTP that is produced but not sent leaves the stored time step unchanged (<xref target="app-a"/>, case 8).  Only the verifier's acceptance confirms authentication, and beyond that single acceptance nothing about the OTP stays valid.</t>
</section>
</section>
<section anchor="sec-6"><name>Resynchronization</name>
<t>This document updates Section 6 of <xref target="RFC6238"/> as follows.</t>
<artwork type="text" name="" align="left"><![CDATA[
=== ADD AT THE END OF SECTION 6 ===
Accepting an OTP found by resynchronization also advances the last
accepted time step.  The drift found by resynchronization does not
allow an OTP whose time step is not later than the last accepted time
step.
=== END ===
]]></artwork>
</section>
<section anchor="sec-7"><name>Implementation Status</name>
<t>[RFC Editor: please remove this section and the reference to RFC 7942 before publication.]</t>
<t>This section reports the status of known implementations of this update at the time of posting of this Internet-Draft, and is based on a proposal described in <xref target="RFC7942"/>.  Listing an implementation here does not imply endorsement by the IETF, and other implementations may exist.</t>
<dl newline="false" spacing="normal" indent="3">
<dt>Implementation:</dt><dd>A Java reference verifier, the class TOTPVerifier in <xref target="app-b"/>, with a sample program and two test programs kept outside this document.  Reference code (prototype), under the Revised BSD License.</dd>
<dt>Coverage:</dt><dd>The check and store of <xref target="sec-5-2"/> in one verifier process, with the time step taken from Unix time.  Not covered: a store shared by several verifier instances, restart and failover, an unreachable store, and resynchronization.</dd>
<dt>Last updated:</dt><dd>6 December 2026.</dd>
</dl>
<t>Test results, using SHA-1 and the secret and time steps of Appendix B of <xref target="RFC6238"/>:</t>
<ul>
<li>All six SHA-1 OTP values of Appendix B of <xref target="RFC6238"/> are reproduced.</li>
<li>The eight cases of <xref target="app-a"/> give the decisions shown there.</li>
<li>An OTP sent again after it was accepted is rejected (case 2).</li>
<li>An OTP for an earlier time step, inside the window, is rejected once a later time step has been accepted (cases 3 and 6), and accepted when none has (cases 4 and 5).</li>
<li>With 32 concurrent attempts of the same OTP, 1 is accepted and 31 are rejected (case 7).  The same held in 200 further runs of 32 attempts.</li>
<li>An OTP that is produced but not sent leaves the stored time step unchanged (case 8).</li>
</ul>
</section>
<section anchor="sec-8"><name>IANA Considerations</name>
<t>This document has no IANA actions.</t>
</section>
</middle>
<back>
<references><name>Normative References</name><reference anchor="RFC2119" target="https://www.rfc-editor.org/info/rfc2119">
          <front>
            <title>Key words for use in RFCs to Indicate Requirement Levels</title>
            <author initials="S." surname="Bradner" fullname="S. Bradner"/>
            <date month="March" year="1997"/>
          </front>
          <seriesInfo name="BCP" value="14"/>
          <seriesInfo name="RFC" value="2119"/>
          <seriesInfo name="DOI" value="10.17487/RFC2119"/>
        </reference>
        <reference anchor="RFC4226" target="https://www.rfc-editor.org/info/rfc4226">
          <front>
            <title>HOTP: An HMAC-Based One-Time Password Algorithm</title>
            <author initials="D." surname="M'Raihi" fullname="D. M'Raihi"/>
            <author initials="M." surname="Bellare" fullname="M. Bellare"/>
            <author initials="F." surname="Hoornaert" fullname="F. Hoornaert"/>
            <author initials="D." surname="Naccache" fullname="D. Naccache"/>
            <author initials="O." surname="Ranen" fullname="O. Ranen"/>
            <date month="December" year="2005"/>
          </front>
          <seriesInfo name="RFC" value="4226"/>
          <seriesInfo name="DOI" value="10.17487/RFC4226"/>
        </reference>
        <reference anchor="RFC6238" target="https://www.rfc-editor.org/info/rfc6238">
          <front>
            <title>TOTP: Time-Based One-Time Password Algorithm</title>
            <author initials="D." surname="M'Raihi" fullname="D. M'Raihi"/>
            <author initials="S." surname="Machani" fullname="S. Machani"/>
            <author initials="M." surname="Pei" fullname="M. Pei"/>
            <author initials="J." surname="Rydell" fullname="J. Rydell"/>
            <date month="May" year="2011"/>
          </front>
          <seriesInfo name="RFC" value="6238"/>
          <seriesInfo name="DOI" value="10.17487/RFC6238"/>
        </reference>
        <reference anchor="RFC8174" target="https://www.rfc-editor.org/info/rfc8174">
          <front>
            <title>Ambiguity of Uppercase vs Lowercase in RFC 2119 Key Words</title>
            <author initials="B." surname="Leiba" fullname="B. Leiba"/>
            <date month="May" year="2017"/>
          </front>
          <seriesInfo name="BCP" value="14"/>
          <seriesInfo name="RFC" value="8174"/>
          <seriesInfo name="DOI" value="10.17487/RFC8174"/>
        </reference></references>
<references><name>Informative References</name>
<reference anchor="RFC7942" target="https://www.rfc-editor.org/info/rfc7942">
<front>
<title>Improving Awareness of Running Code: The Implementation Status Section</title>
<author initials="Y." surname="Sheffer" fullname="Y. Sheffer"/>
<author initials="A." surname="Farrel" fullname="A. Farrel"/>
<date month="July" year="2016"/>
</front>
<seriesInfo name="BCP" value="205"/>
<seriesInfo name="RFC" value="7942"/>
<seriesInfo name="DOI" value="10.17487/RFC7942"/>
</reference>
</references>
<section anchor="app-a"><name>Test Vectors</name>
<t>The values are from Appendix B of <xref target="RFC6238"/>: shared secret "12345678901234567890", SHA-1, 8 digits, time step size 30 seconds, start time 0.  Unix time 1111111109 is time step 37037036 with OTP 07081804, and Unix time 1111111111 is time step 37037037 with OTP 14050471.  The verifier clock reads 1111111111, and the window is the current time step and the one before it.  Cases 1 to 3 use one prover, cases 4 to 6 a second, case 7 a third, and case 8 a fourth.  "none" means no time step has been accepted yet.  A conforming verifier gives these results.</t>
<artwork type="text" name="" align="left"><![CDATA[
Case  Before    OTP (time step)         Decision            After
1     none      14050471 (37037037)     ACCEPT              37037037
2     37037037  14050471 (37037037)     REJECT              37037037
3     37037037  07081804 (37037036)     REJECT              37037037
4     none      07081804 (37037036)     ACCEPT              37037036
5     37037036  14050471 (37037037)     ACCEPT              37037037
6     37037037  07081804 (37037036)     REJECT              37037037
7     none      14050471 x32 at once    1 ACCEPT, 31 REJECT 37037037
8     none      (none sent)             NO CHANGE           none
Time step size: 30 seconds
Verifier clock: Unix time 1111111111 = time step 37037037
Window: time steps 37037036 to 37037037
]]></artwork>
</section>
<section anchor="app-b"><name>Reference Verifier (Java)</name>
<t>This class implements <xref target="sec-5-2"/> and produced the results in <xref target="app-a"/>.</t>
<sourcecode type="java" markers="true" name="TOTPVerifier.java"><![CDATA[
/**
 * Copyright (c) 2026 IETF Trust and the persons identified as
 * authors of the code. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or
 * without modification, is permitted pursuant to, and subject
 * to the license terms contained in, the Revised BSD License
 * set forth in Section 4.e of the IETF Trust's Legal Provisions
 * Relating to IETF Documents
 * (https://trustee.ietf.org/license-info).
 */

import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * TOTP verifier with the rule of Section 5.2 of this update.  The
 * store holds the last accepted time step for each prover (-1 if
 * none).
 */
public class TOTPVerifier {

    private final int digits;
    private final String crypto;     // HmacSHA1, HmacSHA256, ...
    final ConcurrentHashMap<String, AtomicLong> store =
        new ConcurrentHashMap<String, AtomicLong>();

    public TOTPVerifier(int digits, String crypto) {
        this.digits = digits;
        this.crypto = crypto;
    }

    /** The TOTP value for a shared secret and a time step. */
    public static String otp(byte[] sharedSecret, long timeStep,
            int digits, String crypto) {
        try {
            Mac hmac = Mac.getInstance(crypto);
            hmac.init(new SecretKeySpec(sharedSecret, "RAW"));
            byte[] hash = hmac.doFinal(
                ByteBuffer.allocate(8).putLong(timeStep).array());
            long binary = ByteBuffer.wrap(
                hash, hash[hash.length - 1] & 0xf, 4).getInt()
                    & 0x7fffffffL;
            return String.format("%0" + digits + "d",
                binary % (long) Math.pow(10, digits));
        } catch (GeneralSecurityException e) {
            throw new IllegalStateException(e);
        }
    }

    /**
     * Returns true (accept) or false (reject).  firstTimeStep to
     * lastTimeStep is the transmission delay window.
     */
    public boolean validate(String prover, byte[] sharedSecret,
            String otp, long firstTimeStep, long lastTimeStep) {
        AtomicLong last = store.computeIfAbsent(prover,
            x -> new AtomicLong(-1L));
        for (long step = Math.max(firstTimeStep, last.get() + 1);
                step <= lastTimeStep; step++) {
            if (otp(sharedSecret, step, digits, crypto)
                    .equals(otp)) {
                // Check and store in one atomic step.
                long prev = last.get();
                while (prev < step) {
                    if (last.compareAndSet(prev, step)) {
                        return true;
                    }
                    prev = last.get();
                }
                return false;
            }
        }
        return false;
    }
}
]]></sourcecode>
</section>
<section anchor="acknowledgements" numbered="false"><name>Acknowledgements</name>
<t>The author thanks the authors of RFC 6238 and RFC 4226, who did not write, check, or endorse this document.</t>
</section>
</back>
</rfc>
