MEGA Cryptographic Attributes
============================

This document describes the user account key attributes used by the MEGA
protocol (v2 / login variant 2), how they relate to each other, and how
megatools sets them up when it verifies a new account.

Overview
--------

User cryptographic material is split into two categories:

  1. Public attributes   — stored as individual user attributes, readable
                           by other users (pubk, +puEd255, +puCu255,
                           +sigPubk, +sigCu255).

  2. Private keys        — the Ed25519, Cu25519 and RSA private keys,
                           authrings and share keys, stored in the
                           versioned ^!keys attribute (encrypted with a key
                           derived from the master key).  Older clients keep
                           them in the legacy private attributes (*keyring,
                           privk, *!authring, *!authCu255).

Both sets are needed for full account functionality.  The MEGA SDK and
megatools upload the legacy private attributes too (*keyring, privk), for
clients that predate ^!keys.


Individual Public Attributes
----------------------------

These are user attributes stored on the server and returned in the `ug`
API response.  They are not encrypted.

  pubk
    RSA public key (2048-bit, megatools uses e = 257).  Encoded as two
    MPIs (m, e) with 2-byte big-endian bit-length headers,
    base64url-encoded.
    Used by other users for RSA-based share key encryption (legacy).
    Set together with privk: {a:"up", pubk:"<b64>", privk:"<b64>"}.
    `ug` returns it as a plain string, not as {av, v}.

  +puEd255
    Ed25519 public key (32 bytes), base64url-encoded.
    The `+` prefix means it is public and stored unencrypted.
    Used by other users to verify Ed25519 signatures (sigPubk, sigCu255,
    and future signed messages).

  +puCu255
    Curve25519 public key (32 bytes), base64url-encoded.
    Unencrypted.  Used by other users for ECDH chat key exchange.

  +sigPubk
    Ed25519 signature of the RSA public key, proving that the owner of
    the Ed25519 private key also owns the RSA key.  Unencrypted,
    base64url-encoded.

  +sigCu255
    Ed25519 signature of the Curve25519 public key (puCu255), proving
    ownership.  Unencrypted.

  Both signatures are 72 bytes:

    sig = timestamp (8 bytes, big-endian unix time)
          || Ed25519_sign("keyauth" || timestamp || key)   (64 bytes)

  where key is the 32-byte Cu25519 public key for +sigCu255, and for
  +sigPubk the RSA modulus followed by the exponent, as encoded in pubk
  but without the MPI length headers.

All five attributes are set during initial account key generation and
must be present for an account to be considered "fully initialized".


Individual Private Attributes (Legacy)
--------------------------------------

  *keyring
    Private Ed25519 and Cu25519 keys:
      "prEd255"  → 32 bytes Ed25519 seed
      "prCu255"  → 32 bytes Cu25519 private key
    The `*` prefix means it is stored encrypted on the server (see the
    container format below).
    Legacy.  Superseded by ^!keys tags PRIV_ED25519 and PRIV_CU25519.
    Still uploaded for backwards compatibility with older clients.

  privk
    RSA private key (p, q, d, u), serialized as 4 MPIs with 2-byte
    big-endian bit-length headers, padded to a multiple of 16 bytes,
    AES-128-ECB encrypted with MK, base64url-encoded.
    Set via the `up` command together with pubk.  Returned by `us` with
    csid (see Login Response Fields).
    Legacy.  Superseded by ^!keys tag PRIV_RSA.

  *!authring (Ed25519) / *!authCu255
    Contact authentication rings.  Legacy, migrated into ^!keys tags
    AUTHRING_ED25519 and AUTHRING_CU25519.

  Legacy share keys
    Before ^!keys, the keys of outgoing shares came in the `ok` array of
    the file list (`f`): {h, ha, k}, k = AES-128-ECB(MK, share key), ha
    authenticates the handle with MK.  Incoming shares carry their key in
    the `sk` field of the share's node, RSA encrypted.  Migrated into
    ^!keys tag SHAREKEYS; on accounts with ^!keys megatools ignores them
    and uses the keys from ^!keys.

Private attribute container (`*` attributes)
--------------------------------------------

  container = [mode:1][iv][ciphertext][tag]      encrypted with MK
  records   = ([name][0x00][length:2 BE][value])*

  mode selects the AEAD and the iv/tag lengths:

    0x00, 0x03   AES-CCM, iv 12, tag 16
    0x01         AES-CCM, iv 10, tag 16
    0x02, 0x04   AES-CCM, iv 10, tag 8
    0x10         AES-GCM, iv 12, tag 16     (megatools always writes this)
    0x11         AES-GCM, iv 10, tag 8

  A record length of 0xffff means "the rest of the data".


^!keys KeyManager Attribute
===========================

^!keys is the modern versioned container for all private cryptographic
material.  It is a single user attribute (ATTR_KEYS = 37 in the SDK)
stored on the server and returned in `ug` responses ({av, v} with
`ug v:1`).

Key Derivation
--------------

The ^!keys attribute is encrypted with a key derived from the master
key (MK, 16 bytes) using HKDF-SHA256:

  derived_key = HKDF-SHA256(
      salt  = (empty)
      ikm   = master_key (16 bytes)
      info  = [0x01] (1 byte)
      len   = 16 bytes
  )

This derived_key is used for AES-128-GCM encryption/decryption.

Wire Format (Base64-encoded, sent to/received from server)
-----------------------------------------------------------

  ┌─────────┬───────────┬──────────────┬─────────────────────────┐
  │ version │ reserved  │ iv           │ ciphertext + tag        │
  │ 1 byte  │ 1 byte    │ 12 bytes     │ variable                │
  └─────────┴───────────┴──────────────┴─────────────────────────┘

  version     = 20 (KEYMANAGER_VERSION)
  reserved    = 0
  iv          = random 12-byte AES-GCM nonce
  ciphertext  = AES-128-GCM encrypted plaintext
  tag         = AES-128-GCM authentication tag (16 bytes), appended to ciphertext

The entire binary blob is base64url-encoded for transport.

Plaintext Format (TLV Records)
------------------------------

After GCM decryption, the plaintext is a sequence of TLV (Tag-Length-Value)
records.  Each record:

  ┌──────────┬──────────┬───────────────┐
  │ tag      │ length   │ value         │
  │ 1 byte   │ 3 bytes  │ length bytes  │
  └──────────┴──────────┴───────────────┘

  tag    = record type (see tag list below)
  length = big-endian uint24, number of value bytes
  value  = record payload

Note: this is a TLV format (tag, length, value), NOT LTV.

TLV Tags
--------

  Header fields (always present):

  TAG_VERSION          = 1     length=1     uint8 version (must be 1)
  TAG_CREATION_TIME    = 2     length=4     uint32 unix timestamp
  TAG_IDENTITY         = 3     length=8     user handle (binary, 8 bytes)
  TAG_GENERATION       = 4     length=4     uint32 generation counter
  TAG_ATTR             = 5     variable     optional serialized attributes

  Private keys (always present):

  TAG_PRIV_ED25519     = 16    length=32    Ed25519 private seed
  TAG_PRIV_CU25519     = 17    length=32    Cu25519 private key
  TAG_PRIV_RSA         = 18    variable     RSA private key (p, q, d)
                                            serialized as 3 MPIs with
                                            2-byte bit-length headers;
                                            may be empty (accounts that
                                            get their RSA key later)

  Authentication rings:

  TAG_AUTHRING_ED25519 = 32    variable     Ed25519 authring records
  TAG_AUTHRING_CU25519 = 33    variable     Cu25519 authring records
                                            [handle:8][fingerprint:20]
                                            [method:1] each

  Share key management:

  TAG_SHAREKEYS        = 48    variable     share keys for shared folders
  TAG_PENDING_OUTSHARES= 64    variable     pending outgoing shares
  TAG_PENDING_INSHARES = 65    variable     pending incoming shares

  Other:

  TAG_BACKUPS          = 80    variable     folder backup metadata
  TAG_WARNINGS         = 96    variable     cryptographic warnings

megatools keeps records it doesn't use (pending inshares, backups,
warnings, unknown tags, sections it can't parse) and writes them back
unchanged.

Concurrency Control and Checks
------------------------------

^!keys is a versioned attribute.  `ug` returns the stored version string
with the value ({av, v}).  An update is sent with `upv` and the version
it was based on:

  [{a:"upv", "^!keys":["<new blob>", "<version read>"]}]

(without a version when the attribute is created).  The server answers
with the new version string, or EEXPIRED when another client updated
^!keys in between.  megatools then fetches ^!keys again, applies its
change to the fresh copy and retries.

The generation counter (TAG_GENERATION) is incremented with every
commit.  A client remembers the highest generation it has seen (megatools
keeps it in the session cache) and rejects a ^!keys with a lower one as a
downgrade.  The identity (TAG_IDENTITY) must be the account's own user
handle.  A rejected ^!keys doesn't replace any of the keys in memory.


Relationship Between Attributes
===============================

Dependency Map
--------------

  Master Key (MK, 16 bytes)
  ├── password_key (first 16 bytes of the PBKDF2 output)
  │   └── decrypts `k` from us → MK
  ├── encrypts *keyring, *!authring, ... via AES-GCM (container above)
  ├── encrypts privk (legacy) via AES-128-ECB
  └── HKDF-SHA256 → ^!keys encryption key
      └── encrypts ^!keys plaintext via AES-128-GCM

  RSA Keypair
  ├── pubk (public)    → individual attribute, used for share key encryption
  ├── privk (legacy)   → `up` command, AES-ECB encrypted with MK
  └── privk (^!keys)   → TAG_PRIV_RSA, serialized as p, q, d, inside ^!keys

  Ed25519 Keypair
  ├── +puEd255 (pub)   → individual attribute
  ├── priv seed        → TAG_PRIV_ED25519 inside ^!keys
  │                     → *keyring "prEd255" (legacy, backwards compat)
  ├── +sigPubk         → signature of RSA pubk with Ed25519 priv
  └── +sigCu255        → signature of Cu25519 pubk with Ed25519 priv

  Cu25519 Keypair
  ├── +puCu255 (pub)   → individual attribute
  └── priv key         → TAG_PRIV_CU25519 inside ^!keys
                       → *keyring "prCu255" (legacy, backwards compat)

Login Response Fields
---------------------

  `us` (login) response fields:

    k       Master key, AES-128-ECB encrypted with password_key.
    u       User handle (8 bytes, base64url-encoded: 11 characters).

    tsid    Session id, returned for accounts WITHOUT an RSA key on the
            server (brand new).  43 bytes: 16 random bytes, the user
            handle (11 characters), and AES-128-ECB(MK, the 16 random
            bytes).  Used directly as the API session id; the last part
            lets the client check that the server knows the account.

    csid    Session id, RSA-encrypted with the account's public key.
            Returned for accounts WITH an RSA key.  Decrypted with the
            private key from privk; the session id is the first 43 bytes
            of the plaintext, which has the user handle at offset 16.

    privk   RSA private key (p, q, d, u), AES-128-ECB encrypted with MK.
            Returned alongside csid.

    ach     Achievements program flag (boolean, unrelated to keys).

SDK Behavior Notes
------------------

- The MEGA SDK takes the Ed25519/Cu25519 private keys from ^!keys when
  the account has it (generation > 0), and from *keyring only otherwise.

- Public attributes (+puEd255, +puCu255, +sigPubk, +sigCu255) are always
  processed from `ug` regardless of ^!keys state.

- The `pubk` RSA public key is set via the legacy `up` command (not stored
  inside ^!keys) because other users need it independently.

- During new key initialization, the SDK uploads ^!keys, *keyring and the
  public attributes together, *keyring for backwards compatibility with
  older clients that don't support ^!keys.

- Public keys or signatures without their private keys are reported
  ("Incomplete keypair detected"), not replaced.


Key Initialization (reg --verify)
=================================

The verification (megatools reg --verify, register_verify() in
lib/mega.c) confirms the account and sets up all its keys.  It must
tolerate interruption at any step: a crash, network error, or process
kill must not leave the account in an unrecoverable state.  On retry it
re-examines the server state and does what is left.

Core Principle
--------------

^!keys is committed FIRST.  It holds all private keys (Ed25519, Cu25519,
RSA), so once it exists, everything else can be derived from it again.
Nothing public is uploaded before the private keys are durable on the
server.

Every step is either:

  • Read-only (us0, us, ug)  — safe to repeat, returns fresh tokens/data.
  • Derived from ^!keys       — uploaded only when missing or wrong on the
    server; the same keys give the same public attributes.

No state is kept between runs other than what the user passes in (the
state from reg --register holds the password-derived keys, or the email
and password are given).  All decisions are based on the server's answers
to fresh API calls.

Steps
-----

  1. ud2 confirms the signup link.  ENOENT (-9) means the link was used
     already (the account is confirmed): continue.  Otherwise the answer
     must have our email and version 2.

  2. us0 + us log in (v2).  us returns tsid when the server has no RSA
     key for the account, or csid + privk when it has one (the RSA key is
     then taken from privk).

  3. ug (v:1) reads the attributes.

  4. ^!keys:
     a. ^!keys exists: decrypt it (identity and downgrade checks).  If it
        has no RSA key, use the one from privk, or generate one (an error
        if pubk exists without its private key), and commit.
     b. No ^!keys: take the Ed25519/Cu25519 keys from *keyring if there
        is one; if +puEd255 or +puCu255 exist without *keyring, stop with
        an error (the keys may be in use by contacts, they are not
        replaced); otherwise generate them.  Take the RSA key from privk,
        or generate it.  Create ^!keys (generation 1, committed as 2) via
        upv without a version.

  5. The attributes, each derived from ^!keys:
     - pubk + privk: uploaded together when pubk is missing; an existing
       pubk must match the RSA key in ^!keys (else: error).
     - +puEd255, +puCu255: uploaded when missing; existing ones must
       match the private keys (else: error).
     - +sigPubk, +sigCu255: (re)uploaded when missing or when they don't
       verify with +puEd255.
     - *keyring: uploaded when it doesn't hold the same two keys.

Recovery by Failure Point
-------------------------

  (A) After ud2, before the ^!keys commit
      Server: account confirmed, no keys from this run.
      Retry: ud2 → ENOENT.  us returns tsid.  Keys are generated again
      from scratch (nothing of the first attempt was stored).

  (B) upv accepted, answer lost (process killed, connection dropped)
      Server: ^!keys stored.  The retried request has the same request
      id and is answered from the server's request cache when it is
      repeated right away.
      Retry of the verification: ug returns ^!keys → step 4a loads it.

  (C) After ^!keys, during the attribute uploads (step 5)
      Server: ^!keys + any subset of pubk/privk, public keys,
      signatures, *keyring.
      Retry: us returns tsid (pubk/privk not uploaded yet: the RSA key
      comes from ^!keys) or csid + privk (uploaded: the same key).  Step
      5 uploads what is missing and checks what is there.

  (D) Everything done
      Retry: nothing is uploaded (ud2, us0, us, ug only).

  Accounts that were set up by another client in a different order:

  (E) *keyring without ^!keys: the existing Ed25519/Cu25519 keys are kept
      and moved into the new ^!keys.

  (F) Public curve keys without *keyring or ^!keys: the private keys are
      lost.  megatools stops with an error instead of overwriting them.

Private Key Recovery Table
--------------------------

  Key Type     | Stored On Server As         | Recoverable?
  -------------|-----------------------------|---------------------------------
  RSA privk    | `up` privk field (ECB+MK)   | Yes — returned by `us` with csid
  RSA privk    | ^!keys TAG_PRIV_RSA         | Yes — decrypt ^!keys with MK
  Ed25519 seed | *keyring "prEd255" (GCM+MK) | Yes — decrypt *keyring with MK
  Ed25519 seed | ^!keys TAG_PRIV_ED25519     | Yes — decrypt ^!keys with MK
  Cu25519 priv | *keyring "prCu255" (GCM+MK) | Yes — decrypt *keyring with MK
  Cu25519 priv | ^!keys TAG_PRIV_CU25519     | Yes — decrypt ^!keys with MK

  With ^!keys committed first, megatools never stores a public key whose
  private key isn't on the server already.

Server State Transition Diagram
-------------------------------

  [unconfirmed] ──ud2──→ [confirmed, no keys]
                              │
                         us0 + us (tsid)
                              │
                    ┌─────────┴──────────┐
                    │ generate Ed/Cu/RSA │ ─── crash: nothing stored,
                    │ commit ^!keys      │     start over (A)
                    └─────────┬──────────┘
                              │
                    ┌─────────┴──────────┐
                    │ up pubk + privk    │ ─── crash: all keys in ^!keys,
                    │ up +puEd255        │     upload the rest (C)
                    │ up +puCu255        │
                    │ up +sigPubk        │
                    │ up +sigCu255       │
                    │ up *keyring        │
                    └─────────┬──────────┘
                              │
                    [fully initialized]


v2 Registration Key Derivation (uc2)
====================================

The v2 registration flow (uc2 API command) uses PBKDF2-HMAC-SHA512 with
100,000 rounds and a per-user salt to derive a 32-byte key from the
user's password.  This key is split into two 16-byte halves: an
encryption key and an authentication key.

crv — Client Random Value (16 bytes)
-------------------------------------

  A cryptographically random 16-byte value generated by the client at
  registration time (and again at every password change).  It makes
  each user's password-derived key unique.

  The server stores crv and gives the client the salt at login (us0), so
  the client can re-derive the same key.  Without a per-user value, an
  attacker who compromises the server database could precompute password
  hashes against a single static salt.

  Salt derivation:
    salt = SHA256("mega.nz" padded with 'P' to 200 bytes || crv)

  i.e. 216 bytes are hashed: "mega.nz", 193 times 'P', and crv.  The salt
  is 32 bytes (SHA256 output).  Only crv is sent in the uc2 API call;
  us0 returns the salt itself.

hak — Hashed Authentication Key (16 bytes)
-------------------------------------------

  hak = SHA256(auth_key) truncated to the first 16 bytes.

  The full derived key (32 bytes from PBKDF2) is split:
    derived_key[0:16]  = encryption_key (password_key, never sent to
                         the server)
    derived_key[16:32] = auth_key

  hak is what the server STORES to verify the user's password during
  login without ever knowing the password itself.

  Verification flow at login:
    1. Client re-derives auth_key from the password and the salt.
    2. Client sends raw auth_key as `uh` in the us (login) API call.
    3. Server hashes the received auth_key with SHA256, truncates to
       16 bytes, and compares to the stored hak.
    4. If they match, the password is correct.

  This is not a zero-knowledge proof: auth_key itself is sent at every
  login (inside TLS).  The server only stores a hash of it, and auth_key
  doesn't reveal the password_key, which never leaves the client.

k — Encrypted Master Key (16 bytes)
------------------------------------

  k = AES-128-ECB_encrypt(master_key, encryption_key)

  The master key is a separate 16-byte random value that is the
  ultimate root of all user-data encryption (files, folders, RSA
  private key, ^!keys, etc.).  It is independent of the password and
  persists across password changes.

  k is the master key in its "at-rest" encrypted form on the server.
  The server stores k and returns it upon successful login.  Because it
  is encrypted with a key derived from the user's password, the server
  cannot decrypt it — only a client that knows the password can recover
  the master key.

  A password change (megatools passwd) generates a new crv, derives new
  keys from the new password, and replaces all three at once:
  [{a:"up", k:<MK encrypted with the new password_key>, uh:<new hak>,
  crv:<new crv>}] (plus mfa:<code> with 2FA).  The master key, and so
  all files and keys, stay as they are.

Registration Derivation Chain
------------------------------

                         ┌─────────────┐
                         │ RNG → crv   │  (16 random bytes)
                         │ client-side │
                         └──────┬──────┘
                                │
              password ─────────┤
                                │
                                ▼
                   ┌────────────────────────────┐
                   │ salt = SHA256(             │
                   │   "mega.nz" padded with    │
                   │   'P' to 200 bytes         │
                   │   + crv)                   │
                   └──────────────┬─────────────┘
                                  │
                                  ▼
                   ┌─────────────────────────────┐
                   │ derived_key = PBKDF2-HMAC-  │
                   │   SHA512(password, salt,    │
                   │   32 bytes, 100000 rounds)  │
                   └──────────────┬──────────────┘
                                  │
                     ┌────────────┴────────────┐
                     ▼                         ▼
          ┌──────────────────┐    ┌──────────────────┐
          │ encryption_key   │    │ auth_key         │
          │ [0:16]           │    │ [16:32]          │
          │ NEVER sent to    │    │ sent as "uh" at  │
          │ server           │    │ login (raw, 16B) │
          └────────┬─────────┘    └────────┬─────────┘
                   │                       │
              AES-ECB                 SHA256
              encrypt MK              hash, first
                   │                  16 bytes
                   ▼                       ▼
          ┌──────────────────┐    ┌──────────────────┐
          │  k               │    │  hak             │
          │  (encrypted      │    │  (hashed auth    │
          │   master key,    │    │   key, 16B)      │
          │   16 bytes)      │    │                  │
          └────────┬─────────┘    └────────┬─────────┘
                   │                       │
                   ▼                       ▼
          ┌───────────────────────────────────────┐
          │              SERVER                   │
          │  stores: crv, hak, k                  │
          │  at login: receives uh (auth_key),    │
          │    computes SHA256(uh)[0:16], compares│
          │    to stored hak → returns k          │
          └───────────────────────────────────────┘


Login Variant 2 (us0/us) End-to-End Flow
========================================

  Registration (megatools reg --register):
    ere(email)  → -9 (ENOENT) when the address is free
    up {k, ts}  → creates an ephemeral account and returns its user
                  handle; k is MK encrypted with a random key (replaced
                  by uc2), ts = ssc || AES-128-ECB(MK, ssc), ssc random
    us(user handle) → tsid, the ephemeral session
    up {terms, firstname, lastname, name2}  (the account's name)
    client: crv random → salt → PBKDF2 → password_key, auth_key
    uc2 {n, m, crv, hak, k, v:2} → server stores them and sends the
                  confirmation email
    The printed state holds the email and password_key + auth_key, so
    reg --verify can log in without the password.

  Confirmation (megatools reg --verify): see Key Initialization.

  Login:
    us0(user) → server returns {s: salt_b64, v: 2}  ({v: 1} for old
                accounts, which use the legacy key derivation)
    PBKDF2(password, salt, 100000, SHA512) → 32 bytes
      [0:16]  = password_key (AES-128 key, never sent to server)
      [16:32] = uh (sent to server as user hash)
    us(user, uh) → server hashes uh → compares to stored hak → returns k
                   (+ tsid, or csid + privk)

  After login:
    master_key = AES-128-ECB_decrypt(k, password_key)
    master_key is then used for all subsequent data encryption/decryption
