feat(iam): model virtual MFA devices with real TOTP verification (#4820)

Replace the ListMFADevices stub with the virtual MFA device lifecycle:
CreateVirtualMFADevice, ListVirtualMFADevices, DeleteVirtualMFADevice,
EnableMFADevice, DeactivateMFADevice, ResyncMFADevice, ListMFADevices,
and the device tag readers/writers.

The seed is real rather than a placeholder. CreateVirtualMFADevice
generates a 160-bit secret from SecureRandom and returns it as an RFC
4648 base32 string, and EnableMFADevice/ResyncMFADevice verify codes
against it as RFC 6238 TOTP, so a caller that does not hold the seed
cannot enable a device. The codes must be consecutive, as AWS asks for.
Implemented on the JDK's own javax.crypto, with no new dependency.

The TOTP arithmetic is the shared core.common.Totp primitive (#4814):
CognitoTotp keeps its single-code window and attempt budget, and
VirtualMfaCodes holds the consecutive-pair rule that is specific to IAM.

Request shapes are validated against the wire model before the device is
resolved, so a malformed SerialNumber is a ValidationError rather than a
NoSuchEntity, and UserName is enforced as required on Enable and Resync.
VirtualMFADeviceName gets its own validator because it is the one IAM
name type with no documented maximum length, so borrowing the usual
1-to-128 name check would have rejected names AWS accepts.

Device state also reaches the places that report on it: DeleteUser now
returns DeleteConflict while a user still holds a device, GetAccountSummary
counts devices and their assignments, and the credential report's
mfa_active column is backed by real state instead of a constant.

Documented as out of scope: QRCodePNG is not returned (it needs a QR
encoder, and the otpauth URI it encodes is derivable from the seed that
is returned), GetMFADevice takes only FIDO security key ARNs, hardware
and FIDO devices are not modeled, MFA still has no effect on
authorization because the aws:MultiFactorAuth* keys are never populated,
and STS does not accept SerialNumber/TokenCode.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-01 21:17:50 -05:00
1 parent 44e9b1600e
commit c7bb03ace3
14 files changed
+1924 -50

No files matched your search

@@ -16,8 +16,8 @@ import javax.crypto.spec.SecretKeySpec;
*
* <p>Lifted out of {@code CognitoTotp}, which is now a thin view over it, because the same
* arithmetic is needed wherever a service hands a secret to an authenticator app and then verifies
* what the app produces. Cognito's software-token MFA is the only caller today; IAM's virtual MFA
* devices are the reason it lives here rather than inside Cognito.
* what the app produces: Cognito's software-token MFA, and IAM's virtual MFA devices through
* {@code VirtualMfaCodes}.
*
* <p>The secret is real randomness and the codes are really derived from it, so a caller that does
* not hold the secret cannot produce an accepted code. Secrets cross the wire as RFC 4648 base32,
@@ -93,7 +93,7 @@ public final class Totp {
}
/** Whether the value has the shape of a code at all, before any secret is touched. */
static boolean isSixDigits(String code) {
public static boolean isSixDigits(String code) {
if (code == null || code.length() != DIGITS) {
return false;
}
@@ -106,7 +106,7 @@ public final class Totp {
}
/** Length-independent comparison, so a wrong code does not leak its prefix through timing. */
static boolean codeEquals(String expected, String actual) {
public static boolean codeEquals(String expected, String actual) {
return MessageDigest.isEqual(expected.getBytes(StandardCharsets.US_ASCII),
actual.getBytes(StandardCharsets.US_ASCII));
}
@@ -131,7 +131,7 @@ public final class Totp {
return encoded.toString();
}
static byte[] base32Decode(String encoded) {
public static byte[] base32Decode(String encoded) {
int buffer = 0;
int bitsLeft = 0;
byte[] decoded = new byte[encoded.length() * 5 / 8];
@@ -16,15 +16,18 @@ import io.github.hectorvent.floci.services.iam.model.PolicyVersion;
import io.github.hectorvent.floci.services.iam.model.SAMLProvider;
import io.github.hectorvent.floci.services.iam.model.ServiceLastAccessedEntity;
import io.github.hectorvent.floci.services.iam.model.ServiceLastAccessedJob;
import io.github.hectorvent.floci.services.iam.model.VirtualMfaDevice;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
@@ -90,12 +93,23 @@ public class IamQueryHandler {
case "TagUser" -> handleTagUser(params);
case "UntagUser" -> handleUntagUser(params);
case "ListUserTags" -> handleListUserTags(params);
case "ListMFADevices" -> handleListMFADevices(params);
case "CreateLoginProfile" -> handleCreateLoginProfile(params, authorization);
case "GetLoginProfile" -> handleGetLoginProfile(params, authorization);
case "UpdateLoginProfile" -> handleUpdateLoginProfile(params);
case "DeleteLoginProfile" -> handleDeleteLoginProfile(params, authorization);
// Multi-factor authentication
case "CreateVirtualMFADevice" -> handleCreateVirtualMFADevice(params);
case "ListVirtualMFADevices" -> handleListVirtualMFADevices(params);
case "DeleteVirtualMFADevice" -> handleDeleteVirtualMFADevice(params);
case "EnableMFADevice" -> handleEnableMFADevice(params);
case "DeactivateMFADevice" -> handleDeactivateMFADevice(params, authorization);
case "ResyncMFADevice" -> handleResyncMFADevice(params);
case "ListMFADevices" -> handleListMFADevices(params, authorization);
case "TagMFADevice" -> handleTagMFADevice(params);
case "UntagMFADevice" -> handleUntagMFADevice(params);
case "ListMFADeviceTags" -> handleListMFADeviceTags(params);
// Identity providers & server certificates
case "ListSAMLProviders" -> handleListSAMLProviders(authorization);
case "CreateSAMLProvider" -> handleCreateSAMLProvider(params, authorization);
@@ -342,15 +356,129 @@ public class IamQueryHandler {
return Response.ok(AwsQueryResponse.envelope("ListUserTags", AwsNamespaces.IAM, result)).build();
}
private Response handleListMFADevices(MultivaluedMap<String, String> params) {
// MFA device state is not modeled; return the wire-accurate empty result
// (MFADevices list + IsTruncated=false). Real AWS returns NoSuchEntity
// (HTTP 404) for an unknown user — Floci returns an empty list regardless.
/**
* {@code Base32StringSeed} and {@code QRCodePNG} are both typed as base64-encoded binary, so
* the base32 seed string goes out base64-wrapped. The QR code is not returned: encoding a PNG
* would mean a new dependency for an optional field, and the {@code otpauth://} URI it encodes
* is derivable from the seed that is returned. {@code aws iam create-virtual-mfa-device} works
* against this with {@code --bootstrap-method Base32StringSeed}, and fails only when asked for
* the QR code specifically.
*/
private Response handleCreateVirtualMFADevice(MultivaluedMap<String, String> params) {
VirtualMfaDevice device = iamService.createVirtualMfaDevice(
getParam(params, "VirtualMFADeviceName"), getParam(params, "Path"),
extractTags(params, false));
String result = new XmlBuilder()
.start("MFADevices").end("MFADevices")
.elem("IsTruncated", false)
.start("VirtualMFADevice")
.elem("SerialNumber", device.getSerialNumber())
.elem("Base32StringSeed", base64(device.getBase32Seed()))
.raw(tagsElement(new TreeMap<>(device.getTags())))
.end("VirtualMFADevice")
.build();
return Response.ok(AwsQueryResponse.envelope("ListMFADevices", AwsNamespaces.IAM, result)).build();
return Response.ok(AwsQueryResponse.envelope("CreateVirtualMFADevice", AwsNamespaces.IAM, result)).build();
}
/**
* Neither the seed nor the tags appear here: AWS notes that "IAM resource-listing operations
* return a subset of the available attributes for the resource... this operation does not
* return tags", and handing the seed back on an unauthenticated-by-device list call would
* leak the shared secret of every device in the account.
*/
private Response handleListVirtualMFADevices(MultivaluedMap<String, String> params) {
Page<VirtualMfaDevice> page = paginate(
iamService.listVirtualMfaDevices(getParam(params, "AssignmentStatus")), params);
XmlBuilder xml = new XmlBuilder().start("VirtualMFADevices");
for (VirtualMfaDevice device : page.items()) {
xml.start("member").elem("SerialNumber", device.getSerialNumber());
if (device.isAssigned()) {
xml.elem("EnableDate", isoDate(device.getEnableDate()));
// Looked up rather than required: DeleteUser will not let a user go while a device
// is still assigned, so a device pointing at a missing user means the two stores
// have drifted on disk. User is an optional member, so this one device loses it
// instead of the whole account-wide listing failing.
iamService.findUser(device.getUserName())
.ifPresent(user -> xml.start("User").raw(userXml(user, false)).end("User"));
}
xml.end("member");
}
xml.end("VirtualMFADevices").elem("IsTruncated", page.truncated());
if (page.marker() != null) {
xml.elem("Marker", page.marker());
}
return Response.ok(AwsQueryResponse.envelope("ListVirtualMFADevices", AwsNamespaces.IAM, xml.build())).build();
}
private Response handleDeleteVirtualMFADevice(MultivaluedMap<String, String> params) {
iamService.deleteVirtualMfaDevice(getParam(params, "SerialNumber"));
return Response.ok(AwsQueryResponse.envelopeNoResult("DeleteVirtualMFADevice", AwsNamespaces.IAM)).build();
}
private Response handleEnableMFADevice(MultivaluedMap<String, String> params) {
iamService.enableMfaDevice(getParam(params, "UserName"), getParam(params, "SerialNumber"),
getParam(params, "AuthenticationCode1"), getParam(params, "AuthenticationCode2"));
return Response.ok(AwsQueryResponse.envelopeNoResult("EnableMFADevice", AwsNamespaces.IAM)).build();
}
private Response handleDeactivateMFADevice(MultivaluedMap<String, String> params, String authorization) {
// UserName is optional here, unlike on Enable/Resync: "If no user name is included, it
// defaults to the principal making the request."
iamService.deactivateMfaDevice(resolveUserName(params, authorization),
getParam(params, "SerialNumber"));
return Response.ok(AwsQueryResponse.envelopeNoResult("DeactivateMFADevice", AwsNamespaces.IAM)).build();
}
private Response handleResyncMFADevice(MultivaluedMap<String, String> params) {
iamService.resyncMfaDevice(getParam(params, "UserName"), getParam(params, "SerialNumber"),
getParam(params, "AuthenticationCode1"), getParam(params, "AuthenticationCode2"));
return Response.ok(AwsQueryResponse.envelopeNoResult("ResyncMFADevice", AwsNamespaces.IAM)).build();
}
private Response handleListMFADevices(MultivaluedMap<String, String> params, String authorization) {
String userName = resolveUserName(params, authorization);
Page<VirtualMfaDevice> page = paginate(iamService.listMfaDevices(userName), params);
XmlBuilder xml = new XmlBuilder().start("MFADevices");
for (VirtualMfaDevice device : page.items()) {
xml.start("member")
.elem("UserName", device.getUserName())
.elem("SerialNumber", device.getSerialNumber())
.elem("EnableDate", isoDate(device.getEnableDate()))
.end("member");
}
xml.end("MFADevices").elem("IsTruncated", page.truncated());
if (page.marker() != null) {
xml.elem("Marker", page.marker());
}
return Response.ok(AwsQueryResponse.envelope("ListMFADevices", AwsNamespaces.IAM, xml.build())).build();
}
private Response handleTagMFADevice(MultivaluedMap<String, String> params) {
iamService.tagMfaDevice(getParam(params, "SerialNumber"), extractTags(params, false));
return Response.ok(AwsQueryResponse.envelopeNoResult("TagMFADevice", AwsNamespaces.IAM)).build();
}
private Response handleUntagMFADevice(MultivaluedMap<String, String> params) {
iamService.untagMfaDevice(getParam(params, "SerialNumber"), extractTagKeys(params));
return Response.ok(AwsQueryResponse.envelopeNoResult("UntagMFADevice", AwsNamespaces.IAM)).build();
}
/**
* Unlike IAM's other tag readers here, this one honours {@code Marker} and {@code MaxItems}:
* AWS models both on ListMFADeviceTags, and a client asking for a one-item page should be able
* to walk the result. Tags are sorted by key first, as AWS documents ("the returned list of
* tags is sorted by tag key"), so the marker names a stable position.
*/
private Response handleListMFADeviceTags(MultivaluedMap<String, String> params) {
Map<String, String> tags = new TreeMap<>(iamService.listMfaDeviceTags(getParam(params, "SerialNumber")));
Page<Map.Entry<String, String>> page = paginate(List.copyOf(tags.entrySet()), params);
XmlBuilder xml = new XmlBuilder().start("Tags");
for (Map.Entry<String, String> tag : page.items()) {
xml.start("member").elem("Key", tag.getKey()).elem("Value", tag.getValue()).end("member");
}
xml.end("Tags").elem("IsTruncated", page.truncated());
if (page.marker() != null) {
xml.elem("Marker", page.marker());
}
return Response.ok(AwsQueryResponse.envelope("ListMFADeviceTags", AwsNamespaces.IAM, xml.build())).build();
}
private Response handleCreateLoginProfile(MultivaluedMap<String, String> params, String authorization) {
@@ -2362,6 +2490,11 @@ public class IamQueryHandler {
return DateTimeFormatter.ISO_INSTANT.format(instant);
}
/** For a member AWS types as a blob, which the Query protocol carries base64-encoded. */
private String base64(String value) {
return Base64.getEncoder().encodeToString(value.getBytes(StandardCharsets.UTF_8));
}
private Response handleTagInstanceProfile(MultivaluedMap<String, String> params) {
iamService.tagInstanceProfile(getParam(params, "InstanceProfileName"), extractTags(params, false));
return Response.ok(AwsQueryResponse.envelopeNoResult("TagInstanceProfile", AwsNamespaces.IAM)).build();
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.common.AwsPartitions;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ServicePrincipals;
import io.github.hectorvent.floci.core.common.SessionAccountLookup;
import io.github.hectorvent.floci.core.common.Totp;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
@@ -28,6 +29,7 @@ import io.github.hectorvent.floci.services.iam.model.OrganizationRootFeatures;
import io.github.hectorvent.floci.services.iam.model.PolicyVersion;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import io.github.hectorvent.floci.services.iam.model.SessionCredential;
import io.github.hectorvent.floci.services.iam.model.VirtualMfaDevice;
import com.fasterxml.jackson.core.type.TypeReference;
import io.quarkus.runtime.Startup;
import jakarta.annotation.PostConstruct;
@@ -42,6 +44,7 @@ import java.time.Duration;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.Comparator;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@@ -130,6 +133,30 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
private static final Pattern IAM_PATH_PATTERN = Pattern.compile("(/)|(/[\\x21-\\x7E]+/)");
private static final int IAM_PATH_MAX_LENGTH = 512;
private static final int MAX_TAGS_PER_RESOURCE = 50;
/**
* "You can register up to eight MFA devices of any combination of the currently supported MFA
* types" (IAM User Guide). Floci models only virtual devices, so this bounds those alone.
*/
private static final int MAX_MFA_DEVICES_PER_USER = 8;
/** {@code AuthenticationCode1}/{@code 2}: fixed length of 6, pattern {@code [\d]+}. */
private static final Pattern AUTHENTICATION_CODE_PATTERN = Pattern.compile("[0-9]{6}");
/**
* {@code virtualMFADeviceName}: a minimum of 1 and this pattern, with no maximum length. IAM's
* other name types are all capped at 64 or 128; this one is deliberately not.
*/
private static final Pattern VIRTUAL_MFA_DEVICE_NAME_PATTERN = Pattern.compile("[\\w+=,.@-]+");
/** {@code serialNumberType}: 9-256 characters, and a wider pattern than a name, allowing ARNs. */
private static final Pattern SERIAL_NUMBER_PATTERN = Pattern.compile("[\\w+=/:,.@-]+");
private static final int SERIAL_NUMBER_MIN_LENGTH = 9;
private static final int SERIAL_NUMBER_MAX_LENGTH = 256;
/**
* How far the code pair may sit from the current 30-second window. Enabling a device is done
* straight after reading the codes, so a window either side absorbs clock skew and the time
* spent submitting; resync exists for a device that has drifted much further, and is given
* five minutes in each direction.
*/
private static final int ENABLE_DRIFT_STEPS = 1;
private static final int RESYNC_DRIFT_STEPS = 10;
private static final String ROOT_FEATURES_KEY = "org-root-features";
private static final String CREDENTIAL_REPORT_KEY = "credential-report";
/** AWS generates a fresh report only if the most recent one is older than this. */
@@ -172,6 +199,15 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
* one partition is never handed to a caller in another.
*/
private final StorageBackend<String, CredentialReport> credentialReports;
/** Virtual MFA devices, keyed by serial number, which for a virtual device is its own ARN. */
private final StorageBackend<String, VirtualMfaDevice> virtualMfaDevices;
/**
* Guards every check-then-write on an MFA device. Assignment is the reason it has to exist:
* EnableMFADevice reads the device to confirm it is unassigned and reads the user's device
* count to confirm it is under the quota, then writes. Two requests racing the same free
* device would otherwise both see it unassigned and the second would silently steal it.
*/
private final Object mfaDeviceLock = new Object();
private final RegionResolver regionResolver;
private final boolean seedDeployerPrincipal;
private final String seededAccountAlias;
@@ -204,6 +240,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
storageFactory.create("iam", "iam-slr-deletions.json", new TypeReference<>() {}),
storageFactory.create("iam", "iam-org-root-features.json", new TypeReference<>() {}),
storageFactory.create("iam", "iam-credential-reports.json", new TypeReference<>() {}),
storageFactory.create("iam", "iam-virtual-mfa-devices.json", new TypeReference<>() {}),
regionResolver,
config.services().iam().seedDeployerPrincipal(),
config.services().iam().accountAlias().orElse(null)
@@ -233,7 +270,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
this(users, groups, roles, policies, accessKeys, instanceProfiles, sessions,
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), regionResolver, seedDeployerPrincipal, null);
new InMemoryStorage<>(), new InMemoryStorage<>(), regionResolver,
seedDeployerPrincipal, null);
}
// 8-backend constructor (no org-root-features): kept for existing callers/tests;
@@ -255,7 +293,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
this(users, groups, roles, policies, accessKeys, instanceProfiles, sessions,
accountAliases, passwordPolicies, new InMemoryStorage<>(), oidcProviders,
serviceLinkedRoleDeletions, new InMemoryStorage<>(), new InMemoryStorage<>(),
regionResolver, seedDeployerPrincipal, seededAccountAlias);
new InMemoryStorage<>(), regionResolver, seedDeployerPrincipal, seededAccountAlias);
}
// 9-backend constructor (no alias/OIDC/SLR backends): kept for existing callers/tests;
@@ -274,7 +312,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
this(users, groups, roles, policies, accessKeys, instanceProfiles, sessions,
new InMemoryStorage<>(), passwordPolicies, new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), orgRootFeatures,
new InMemoryStorage<>(), regionResolver, seedDeployerPrincipal, null);
new InMemoryStorage<>(), new InMemoryStorage<>(), regionResolver,
seedDeployerPrincipal, null);
}
IamService(StorageBackend<String, IamUser> users,
@@ -291,6 +330,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
StorageBackend<String, String> serviceLinkedRoleDeletions,
StorageBackend<String, OrganizationRootFeatures> orgRootFeatures,
StorageBackend<String, CredentialReport> credentialReports,
StorageBackend<String, VirtualMfaDevice> virtualMfaDevices,
RegionResolver regionResolver,
boolean seedDeployerPrincipal,
String seededAccountAlias) {
@@ -308,6 +348,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
this.serviceLinkedRoleDeletions = serviceLinkedRoleDeletions;
this.orgRootFeatures = orgRootFeatures;
this.credentialReports = credentialReports;
this.virtualMfaDevices = virtualMfaDevices;
this.regionResolver = regionResolver;
this.seedDeployerPrincipal = seedDeployerPrincipal;
this.seededAccountAlias = seededAccountAlias;
@@ -474,7 +515,15 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must delete access keys first.", 409);
}
users.delete(userName);
// Held across the delete, not just the check: EnableMFADevice confirms the user under this
// same lock, so the two cannot interleave into a device assigned to a deleted user.
synchronized (mfaDeviceLock) {
if (!mfaDevicesForUser(userName).isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must deactivate MFA device first.", 409);
}
users.delete(userName);
}
LOG.infov("Deleted IAM user: {0}", userName);
}
@@ -511,11 +560,24 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
"User with name " + newUserName + " already exists.", 409);
}
List<AccessKey> keysToMove = userAccessKeys(userName);
users.delete(userName);
user.setUserName(newUserName);
if (newPath != null) user.setPath(normalizePath(newPath));
user.setArn(iamArnBeside(user.getArn(), "user", user.getPath(), newUserName));
users.put(newUserName, user);
// The rename publishes the user under its new name and moves its MFA devices to
// match. Both happen under the MFA lock, because DeleteUser checks for devices and
// removes the user under that same lock: split across it, a DeleteUser for the new
// name could land after the user is published but before the devices follow, see
// none, and delete a user whose device is about to be reassigned to it.
synchronized (mfaDeviceLock) {
users.delete(userName);
user.setUserName(newUserName);
if (newPath != null) {
user.setPath(normalizePath(newPath));
}
user.setArn(iamArnBeside(user.getArn(), "user", user.getPath(), newUserName));
users.put(newUserName, user);
for (VirtualMfaDevice device : mfaDevicesForUser(userName)) {
device.setUserName(newUserName);
virtualMfaDevices.put(device.getSerialNumber(), device);
}
}
loginProfiles.get(userName).ifPresent(profile -> {
loginProfiles.delete(userName);
profile.setUserName(newUserName);
@@ -1133,9 +1195,9 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
* keys; quota values are cross-checked against AWS's published IAM service quotas
* (docs.aws.amazon.com/general/latest/gr/iam-service.html), though floci itself enforces
* only the 5-versions-per-policy cap in {@link #createPolicyVersion}. Resources floci does
* not track at all (MFA devices, SAML providers, server certificates, account password - all
* stub-empty elsewhere in this handler) are reported as zero rather than omitted, so callers
* indexing into the full AWS field set don't hit a missing-key error.
* not track at all (server certificates, account password - stub-empty elsewhere in this
* handler) are reported as zero rather than omitted, so callers indexing into the full AWS
* field set don't hit a missing-key error.
*/
public Map<String, Long> getAccountSummary() {
long localPolicyCount = 0;
@@ -1176,8 +1238,12 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
summary.put("ServerCertificates", 0L);
summary.put("ServerCertificatesQuota", 20L);
summary.put("Providers", (long) oidcProviders.scan(k -> true).size());
summary.put("MFADevices", 0L);
summary.put("MFADevicesInUse", 0L);
List<VirtualMfaDevice> mfaDevices = virtualMfaDevices.scan(k -> true);
summary.put("MFADevices", (long) mfaDevices.size());
summary.put("MFADevicesInUse", mfaDevices.stream().filter(VirtualMfaDevice::isAssigned).count());
// AWS reports whether the *root* user has MFA enabled, not whether IAM users do. Floci
// does not model root credentials, so this stays false however many user devices exist,
// for the same reason AccountAccessKeysPresent below does.
summary.put("AccountMFAEnabled", 0L);
// AWS reports whether the root account has access keys, not whether IAM users do.
// Floci does not model root access keys, so this remains false even when user keys exist.
@@ -1952,6 +2018,275 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
}
// Virtual MFA devices
// =========================================================================
/**
* Creates an unassigned virtual MFA device. The seed is real randomness, not a placeholder:
* AWS hands it out as {@code Base32StringSeed} precisely so an authenticator app can be
* programmed from it, and {@link #enableMfaDevice} then verifies codes actually derived from
* it. A caller that seeds a TOTP app from a Floci device gets working codes.
*/
public VirtualMfaDevice createVirtualMfaDevice(String name, String path, Map<String, String> tags) {
validateVirtualMfaDeviceName(name);
validateIamPath(path, "Path");
String normalizedPath = normalizePath(path);
// The serial number is the ARN, and the ARN embeds the path, so two devices of the same
// name under different paths are genuinely different devices, as AWS says: "Use with
// path to uniquely identify a virtual MFA device."
String serialNumber = iamArn("mfa", normalizedPath, name);
// AWS's own model leaves a gap here: virtualMFADeviceName has no maximum length, but the
// serial number it mints is a serialNumberType, capped at 256. A long-but-valid name would
// therefore produce a device whose serial every other MFA operation rejects, so it could
// never be enabled, tagged or deleted. Floci refuses it at creation instead of handing back
// an unusable device; the limit named is the serial's, since the name itself has none.
if (serialNumber.length() > SERIAL_NUMBER_MAX_LENGTH) {
throw new AwsException("ValidationError",
"VirtualMFADeviceName and Path together must produce a serial number of at most "
+ SERIAL_NUMBER_MAX_LENGTH + " characters; " + serialNumber.length()
+ " were produced.", 400);
}
if (tags != null && tags.size() > MAX_TAGS_PER_RESOURCE) {
throw new AwsException("LimitExceeded",
"Cannot exceed quota for TagsPerMFADevice: " + MAX_TAGS_PER_RESOURCE, 409);
}
VirtualMfaDevice device = new VirtualMfaDevice();
device.setSerialNumber(serialNumber);
device.setDeviceName(name);
device.setPath(normalizedPath);
device.setBase32Seed(Totp.newSecret());
device.setTags(tags);
synchronized (mfaDeviceLock) {
if (virtualMfaDevices.get(serialNumber).isPresent()) {
throw new AwsException("EntityAlreadyExists",
"MFADevice entity at the same path and name already exists.", 409);
}
virtualMfaDevices.put(serialNumber, device);
}
LOG.infov("Created virtual MFA device: {0}", serialNumber);
return device;
}
/**
* Every virtual MFA device in the account, filtered by assignment. {@code assignmentStatus}
* may be {@code Assigned}, {@code Unassigned} or {@code Any}; null defaults to {@code Any}.
*/
public List<VirtualMfaDevice> listVirtualMfaDevices(String assignmentStatus) {
String status = assignmentStatus == null || assignmentStatus.isBlank() ? "Any" : assignmentStatus;
if (!status.equals("Any") && !status.equals("Assigned") && !status.equals("Unassigned")) {
throw new AwsException("ValidationError",
"1 validation error detected: Value '" + assignmentStatus
+ "' at 'assignmentStatus' failed to satisfy constraint: "
+ "Member must satisfy enum value set: [Any, Unassigned, Assigned]", 400);
}
return virtualMfaDevices.scan(k -> true).stream()
.filter(d -> switch (status) {
case "Assigned" -> d.isAssigned();
case "Unassigned" -> !d.isAssigned();
default -> true;
})
.sorted(Comparator.comparing(VirtualMfaDevice::getSerialNumber))
.toList();
}
/**
* Deletes a virtual MFA device. AWS requires it to be deactivated first: "You must deactivate
* a user's virtual MFA device before you can delete it", so a still-assigned device is the
* documented DeleteConflict rather than a silent detach.
*/
public void deleteVirtualMfaDevice(String serialNumber) {
validateSerialNumber(serialNumber);
synchronized (mfaDeviceLock) {
VirtualMfaDevice device = getVirtualMfaDevice(serialNumber);
if (device.isAssigned()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must deactivate the MFA device from user "
+ device.getUserName() + " first.", 409);
}
virtualMfaDevices.delete(serialNumber);
}
LOG.infov("Deleted virtual MFA device: {0}", serialNumber);
}
/**
* Assigns a device to a user, after checking the two codes really came from its seed. The
* codes must be consecutive, which is what AWS asks for ("a subsequent authentication code"),
* so a caller replaying one code twice is rejected the way a real device's user would be.
*/
public void enableMfaDevice(String userName, String serialNumber, String code1, String code2) {
validateIamResourceName(userName, "UserName");
validateSerialNumber(serialNumber);
validateAuthenticationCode(code1, "AuthenticationCode1");
validateAuthenticationCode(code2, "AuthenticationCode2");
synchronized (mfaDeviceLock) {
// The user's existence is confirmed under the same lock DeleteUser checks for devices
// under. Checked outside it, a DeleteUser that saw no devices could remove the user
// between that check and this write, leaving a device assigned to nobody, and one
// that could never be freed, since deactivating it resolves the user first.
getUser(userName);
VirtualMfaDevice device = getVirtualMfaDevice(serialNumber);
if (device.isAssigned()) {
throw new AwsException("EntityAlreadyExists",
"Device with serial number " + serialNumber + " is already assigned to user "
+ device.getUserName() + ".", 409);
}
if (mfaDevicesForUser(userName).size() >= MAX_MFA_DEVICES_PER_USER) {
throw new AwsException("LimitExceeded",
"Cannot exceed quota for MFADevicesPerUser: " + MAX_MFA_DEVICES_PER_USER, 409);
}
// Codes are checked last, so a request that would be rejected for the device's state
// does not depend on the caller having got the codes right.
requireConsecutiveCodes(device, code1, code2, ENABLE_DRIFT_STEPS);
device.setUserName(userName);
device.setEnableDate(Instant.now());
virtualMfaDevices.put(serialNumber, device);
}
LOG.infov("Enabled MFA device {0} for user {1}", serialNumber, userName);
}
/**
* Detaches a device from its user, leaving the device itself in place. AWS "removes it from
* association with the user name for which it was originally enabled", it does not delete it.
* The seed survives, so the same authenticator entry keeps working if it is re-enabled.
*/
public void deactivateMfaDevice(String userName, String serialNumber) {
validateSerialNumber(serialNumber);
getUser(userName);
synchronized (mfaDeviceLock) {
VirtualMfaDevice device = getVirtualMfaDevice(serialNumber);
if (!userName.equals(device.getUserName())) {
throw new AwsException("NoSuchEntity",
"Device with serial number " + serialNumber + " is not assigned to user "
+ userName + ".", 404);
}
device.setUserName(null);
device.setEnableDate(null);
virtualMfaDevices.put(serialNumber, device);
}
LOG.infov("Deactivated MFA device {0} for user {1}", serialNumber, userName);
}
/**
* Re-synchronizes an assigned device. This is the same pair-of-codes check as
* {@link #enableMfaDevice}, over a wider drift window: a device needing resync is by
* definition one whose clock has wandered, so accepting only the current window would reject
* exactly the case the operation exists to fix.
*/
public void resyncMfaDevice(String userName, String serialNumber, String code1, String code2) {
validateIamResourceName(userName, "UserName");
validateSerialNumber(serialNumber);
validateAuthenticationCode(code1, "AuthenticationCode1");
getUser(userName);
validateAuthenticationCode(code2, "AuthenticationCode2");
synchronized (mfaDeviceLock) {
VirtualMfaDevice device = getVirtualMfaDevice(serialNumber);
if (!userName.equals(device.getUserName())) {
throw new AwsException("NoSuchEntity",
"Device with serial number " + serialNumber + " is not assigned to user "
+ userName + ".", 404);
}
requireConsecutiveCodes(device, code1, code2, RESYNC_DRIFT_STEPS);
}
}
/** The MFA devices assigned to a user, which is what ListMFADevices returns. */
public List<VirtualMfaDevice> listMfaDevices(String userName) {
getUser(userName);
return mfaDevicesForUser(userName);
}
public void tagMfaDevice(String serialNumber, Map<String, String> newTags) {
validateSerialNumber(serialNumber);
synchronized (mfaDeviceLock) {
VirtualMfaDevice device = getVirtualMfaDevice(serialNumber);
device.setTags(mergeTagsWithinQuota(device.getTags(), newTags, "TagsPerMFADevice", false));
virtualMfaDevices.put(serialNumber, device);
}
}
public void untagMfaDevice(String serialNumber, List<String> tagKeys) {
validateSerialNumber(serialNumber);
synchronized (mfaDeviceLock) {
VirtualMfaDevice device = getVirtualMfaDevice(serialNumber);
Map<String, String> remaining = new LinkedHashMap<>(device.getTags());
if (tagKeys != null) {
tagKeys.forEach(remaining::remove);
}
device.setTags(remaining);
virtualMfaDevices.put(serialNumber, device);
}
}
public Map<String, String> listMfaDeviceTags(String serialNumber) {
validateSerialNumber(serialNumber);
return getVirtualMfaDevice(serialNumber).getTags();
}
public VirtualMfaDevice getVirtualMfaDevice(String serialNumber) {
if (serialNumber == null) {
throw new AwsException("NoSuchEntity",
"The MFA device with serial number null cannot be found.", 404);
}
return virtualMfaDevices.get(serialNumber)
.orElseThrow(() -> new AwsException("NoSuchEntity",
"The MFA device with serial number " + serialNumber + " cannot be found.", 404));
}
private List<VirtualMfaDevice> mfaDevicesForUser(String userName) {
return virtualMfaDevices.scan(k -> true).stream()
.filter(d -> userName.equals(d.getUserName()))
.sorted(Comparator.comparing(VirtualMfaDevice::getSerialNumber))
.toList();
}
private void validateAuthenticationCode(String code, String paramName) {
if (code == null || !AUTHENTICATION_CODE_PATTERN.matcher(code).matches()) {
throw new AwsException("ValidationError",
paramName + " must be exactly 6 digits.", 400);
}
}
/**
* {@code virtualMFADeviceName} carries a minimum and a pattern but, unlike every other IAM
* name type, no maximum length. So this cannot reuse
* {@link #validateIamResourceName(String, String)}: capping the name at 128 would reject a
* name AWS accepts.
*/
private void validateVirtualMfaDeviceName(String name) {
if (name == null || name.isEmpty() || !VIRTUAL_MFA_DEVICE_NAME_PATTERN.matcher(name).matches()) {
throw new AwsException("ValidationError",
"VirtualMFADeviceName must be at least 1 character matching [\\w+=,.@-].", 400);
}
}
/**
* {@code serialNumberType}: 9 to 256 characters of {@code [\w+=/:,.@-]}. Checked before the
* device is looked up, so a malformed serial number is the ValidationError AWS returns rather
* than a NoSuchEntity for a device that could never have existed under that name.
*/
private void validateSerialNumber(String serialNumber) {
if (serialNumber == null
|| serialNumber.length() < SERIAL_NUMBER_MIN_LENGTH
|| serialNumber.length() > SERIAL_NUMBER_MAX_LENGTH
|| !SERIAL_NUMBER_PATTERN.matcher(serialNumber).matches()) {
throw new AwsException("ValidationError",
"SerialNumber must be " + SERIAL_NUMBER_MIN_LENGTH + "-" + SERIAL_NUMBER_MAX_LENGTH
+ " characters matching [\\w+=/:,.@-].", 400);
}
}
/**
* Rejects the request unless the two codes are consecutive outputs of the device's seed,
* allowing the counter to start anywhere within {@code driftSteps} of the current window.
*/
private void requireConsecutiveCodes(VirtualMfaDevice device, String code1, String code2, int driftSteps) {
if (!VirtualMfaCodes.matchesConsecutiveCodes(device.getBase32Seed(), code1, code2,
driftSteps, Instant.now())) {
throw new AwsException("InvalidAuthenticationCode",
"Invalid MFA one time pass code.", 403);
}
}
// OIDC Identity Providers
// =========================================================================
@@ -3158,10 +3493,11 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
* The 23 columns AWS documents for the credential report, in order, always led by the
* {@code <root_account>} row. Floci does not model root account credentials at all (see
* {@code GetAccountSummary}'s {@code AccountPasswordPresent}/{@code AccountAccessKeysPresent},
* always zero), so that row is always unused/not-present placeholders. MFA devices and X.509
* signing certificates are not modeled for IAM users either, so those columns are always
* {@code FALSE}/{@code N/A} for every row; access key last-used tracking (date, region,
* service) is not modeled, so those three columns are always {@code N/A} too.
* always zero), so that row is always unused/not-present placeholders, including its
* {@code mfa_active}, which reports on root rather than on any IAM user's device. X.509
* signing certificates are not modeled, so those columns are always {@code FALSE}/{@code N/A}
* for every row; access key last-used tracking (date, region, service) is not modeled, so
* those three columns are always {@code N/A} too.
*/
private String buildCredentialReportCsv() {
StringBuilder csv = new StringBuilder(
@@ -3204,7 +3540,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
passwordLastUsedField(user, passwordEnabled),
passwordEnabled ? isoDate(passwordLastChanged(loginProfile.get())) : "N/A",
passwordNextRotationField(loginProfile, passwordEnabled),
"FALSE",
mfaDevicesForUser(user.getUserName()).isEmpty() ? "FALSE" : "TRUE",
accessKeyActiveField(key1), accessKeyRotatedField(key1), "N/A", "N/A", "N/A",
accessKeyActiveField(key2), accessKeyRotatedField(key2), "N/A", "N/A", "N/A",
"FALSE", "N/A", "FALSE", "N/A",
@@ -0,0 +1,42 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.core.common.Totp;
import java.time.Instant;
/**
* The one authentication-code rule specific to IAM. EnableMFADevice and ResyncMFADevice each take
* two codes, and AWS asks for the second to be "a subsequent authentication code", so the pair has
* to be consecutive outputs of the device's seed. Checking each code on its own would accept the
* same code submitted twice, which no real authenticator would produce.
*
* <p>The seed and the code arithmetic itself are {@link Totp}, shared with Cognito's
* software-token MFA.
*/
final class VirtualMfaCodes {
private VirtualMfaCodes() {
}
/**
* Whether {@code code1} and {@code code2} are two consecutive passwords from
* {@code base32Seed}, with the pair allowed to start up to {@code driftSteps} windows either
* side of the one current at {@code now}.
*/
static boolean matchesConsecutiveCodes(String base32Seed, String code1, String code2,
int driftSteps, Instant now) {
if (base32Seed == null || !Totp.isSixDigits(code1) || !Totp.isSixDigits(code2)) {
return false;
}
long current = Totp.stepAt(now);
// The pair is read as (previous window, current window), so the undrifted case has code1
// one step back; drift widens the search symmetrically around that.
for (long offset = -driftSteps - 1; offset <= driftSteps - 1; offset++) {
if (Totp.codeEquals(Totp.codeAt(base32Seed, current + offset), code1)
&& Totp.codeEquals(Totp.codeAt(base32Seed, current + offset + 1), code2)) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,59 @@
package io.github.hectorvent.floci.services.iam.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* A virtual MFA device, keyed by its serial number, which for a virtual device is its own ARN,
* {@code arn:aws:iam::<account>:mfa/<name>}.
*
* <p>A device exists independently of any user: CreateVirtualMFADevice makes it unassigned, and
* EnableMFADevice is what attaches it to one. {@code userName} and {@code enableDate} are therefore
* both null until then, and null again after DeactivateMFADevice. That pair is exactly what
* ListVirtualMFADevices filters on with {@code AssignmentStatus}.
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class VirtualMfaDevice {
private String serialNumber;
private String deviceName;
private String path = "/";
/** The base32 secret, as handed out in {@code Base32StringSeed} and used to compute TOTP codes. */
private String base32Seed;
/** The assigned user, or null while the device is unassigned. */
private String userName;
/** When the device was assigned, or null while it is unassigned. */
private Instant enableDate;
private Instant createDate = Instant.now();
private Map<String, String> tags = new ConcurrentHashMap<>();
public VirtualMfaDevice() {}
public String getSerialNumber() { return serialNumber; }
public void setSerialNumber(String serialNumber) { this.serialNumber = serialNumber; }
public String getDeviceName() { return deviceName; }
public void setDeviceName(String deviceName) { this.deviceName = deviceName; }
public String getPath() { return path; }
public void setPath(String path) { this.path = path; }
public String getBase32Seed() { return base32Seed; }
public void setBase32Seed(String base32Seed) { this.base32Seed = base32Seed; }
public String getUserName() { return userName; }
public void setUserName(String userName) { this.userName = userName; }
public Instant getEnableDate() { return enableDate; }
public void setEnableDate(Instant enableDate) { this.enableDate = enableDate; }
public Instant getCreateDate() { return createDate; }
public void setCreateDate(Instant createDate) { this.createDate = createDate; }
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) {
this.tags = tags == null ? new ConcurrentHashMap<>() : new ConcurrentHashMap<>(tags);
}
/** Whether the device is attached to a user, which is what {@code AssignmentStatus} selects on. */
public boolean isAssigned() {
return userName != null;
}
}