-
Notifications
You must be signed in to change notification settings - Fork 0
잠금 캡슐 종단간 암호화와 Shamir 키 분산 구현 #33
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
6083e31
feat: #32 :: implement shamir's secret sharing over gf(256)
cfcromn 261f3ec
chore: #32 :: add key share schema and capsule encryption mode
cfcromn b19afd7
feat: #32 :: encrypt locked capsules client-side with shamir key shares
cfcromn 346759b
test: #32 :: cover the encryption policy and the end-to-end key round…
cfcromn cbd610d
fix: #32 :: stop sending the lock secret to the server and validate s…
cfcromn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
107 changes: 107 additions & 0 deletions
107
src/main/kotlin/team/cklob/mudda/domain/timecapsule/application/CapsuleEncryptionPolicy.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| package team.cklob.mudda.domain.timecapsule.application | ||
|
|
||
| import org.springframework.stereotype.Component | ||
| import java.util.Base64 | ||
| import team.cklob.mudda.domain.timecapsule.domain.type.CapsuleEncryptionMode | ||
| import team.cklob.mudda.domain.timecapsule.domain.type.CapsuleLockType | ||
| import team.cklob.mudda.domain.timecapsule.presentation.request.CreateCapsuleRequest | ||
| import team.cklob.mudda.domain.timecapsule.presentation.request.KeyShareRequest | ||
| import team.cklob.mudda.global.exception.BusinessException | ||
| import team.cklob.mudda.global.exception.ErrorCode | ||
|
|
||
| // Decides which encryption mode a capsule gets and refuses payloads that would quietly break the | ||
| // guarantee the mode advertises. Kept out of CreateCapsuleService so the whole rule set reads in one | ||
| // place -- this is the boundary CLAUDE.md asks to keep explicit rather than scattered. | ||
| @Component | ||
| class CapsuleEncryptionPolicy { | ||
| fun resolveMode(lockType: CapsuleLockType): CapsuleEncryptionMode = when (lockType) { | ||
| // An unlocked capsule opens on location alone, and the server stores the location. Any secret it | ||
| // withheld from itself it could re-derive, so end-to-end encryption is not achievable here and | ||
| // claiming it would be worse than not offering it. | ||
| CapsuleLockType.NONE -> CapsuleEncryptionMode.SERVER_ENVELOPE | ||
| CapsuleLockType.PASSWORD, CapsuleLockType.QUESTION -> CapsuleEncryptionMode.CLIENT_E2E | ||
| } | ||
|
|
||
| fun validate(request: CreateCapsuleRequest, mode: CapsuleEncryptionMode) { | ||
| validateQuestionText(request) | ||
| when (mode) { | ||
| CapsuleEncryptionMode.SERVER_ENVELOPE -> validateServerEnvelope(request) | ||
| CapsuleEncryptionMode.CLIENT_E2E -> validateClientE2e(request) | ||
| } | ||
| } | ||
|
|
||
| // The question is the only lock field the server still receives -- it is prompt text shown to the | ||
| // opener, never the answer. | ||
| private fun validateQuestionText(request: CreateCapsuleRequest) { | ||
| val valid = when (request.lockType) { | ||
| CapsuleLockType.QUESTION -> !request.question.isNullOrBlank() | ||
| CapsuleLockType.NONE, CapsuleLockType.PASSWORD -> request.question == null | ||
| } | ||
| if (!valid) throw BusinessException(ErrorCode.INVALID_CAPSULE_ENCRYPTION) | ||
| } | ||
|
|
||
| private fun validateServerEnvelope(request: CreateCapsuleRequest) { | ||
| if (request.content.isNullOrBlank()) throw BusinessException(ErrorCode.INVALID_CAPSULE_ENCRYPTION) | ||
| // Rejected rather than ignored: silently dropping key material would leave the client believing it | ||
| // created an end-to-end capsule. | ||
| if (request.contentCipher != null || !request.keyShares.isNullOrEmpty() || request.keyThreshold != null) { | ||
| throw BusinessException(ErrorCode.INVALID_CAPSULE_ENCRYPTION) | ||
| } | ||
| } | ||
|
|
||
| private fun validateClientE2e(request: CreateCapsuleRequest) { | ||
| // The server must never receive a plaintext body for a capsule it is not supposed to be able to read. | ||
| if (request.content != null) throw BusinessException(ErrorCode.INVALID_CAPSULE_ENCRYPTION) | ||
| if (request.contentCipher.isNullOrBlank()) throw BusinessException(ErrorCode.INVALID_CAPSULE_ENCRYPTION) | ||
|
|
||
| val shares = request.keyShares | ||
| val threshold = request.keyThreshold | ||
| if (shares.isNullOrEmpty() || threshold == null) throw BusinessException(ErrorCode.INVALID_CAPSULE_ENCRYPTION) | ||
| if (shares.map { it.index }.toSet().size != shares.size) throw BusinessException(ErrorCode.INVALID_CAPSULE_ENCRYPTION) | ||
|
|
||
| // The guarantee this mode advertises is that the server cannot reconstruct the key on its own. A | ||
| // wrapped share does not count: it is ciphertext under a key derived from the lock secret, which the | ||
| // server only ever sees as a bcrypt hash. Enforced here rather than trusted to the client, because a | ||
| // client bug that sent every share in the clear would silently downgrade the capsule to plaintext | ||
| // while still reporting it as end-to-end. | ||
| val usableByServer = shares.count { it.isWrapped == false } | ||
| if (usableByServer >= threshold) throw BusinessException(ErrorCode.SERVER_HOLDS_KEY_QUORUM) | ||
|
|
||
| // Symmetrically, at least one wrapped share has to be present: otherwise the client has no way to | ||
| // reach the threshold either and the capsule would be unopenable by anyone. | ||
| if (shares.none { it.isWrapped == true }) throw BusinessException(ErrorCode.INVALID_CAPSULE_ENCRYPTION) | ||
|
|
||
| validateWrappedShapes(shares) | ||
| } | ||
|
|
||
| // `isWrapped` is a client assertion, and the server fundamentally cannot verify it: well-encrypted | ||
| // bytes are indistinguishable from random ones, so no check can prove a share is really wrapped. What | ||
| // is checkable is its shape. A share wrapped with AES-256-GCM as the protocol specifies carries a | ||
| // 12-byte nonce and a 16-byte tag on top of the plaintext share, so a wrapped share must be exactly | ||
| // AEAD_OVERHEAD_BYTES longer than a plaintext one. | ||
| // | ||
| // This catches the realistic failure -- a client bug that labels raw shares as wrapped and silently | ||
| // downgrades the capsule to server-readable. It does not stop a client that deliberately pads raw | ||
| // bytes to the right length. That residual case is accepted: a client lying here only exposes its own | ||
| // capsule, whose secret it already holds, so the guarantee is precisely "the server cannot read a | ||
| // capsule whose owner followed the protocol". | ||
| private fun validateWrappedShapes(shares: List<KeyShareRequest>) { | ||
| val decoded = shares.map { | ||
| it to runCatching { Base64.getDecoder().decode(it.data) } | ||
| .getOrElse { throw BusinessException(ErrorCode.INVALID_CAPSULE_ENCRYPTION) } | ||
| } | ||
| // With no plaintext share there is no baseline length to compare against, and the server holding | ||
| // zero usable shares is already the strongest case, so there is nothing left to check. | ||
| val plainLength = decoded.firstOrNull { (share, _) -> share.isWrapped == false }?.second?.size ?: return | ||
|
|
||
| decoded.forEach { (share, bytes) -> | ||
| val expected = if (share.isWrapped == true) plainLength + AEAD_OVERHEAD_BYTES else plainLength | ||
| if (bytes.size != expected) throw BusinessException(ErrorCode.INVALID_CAPSULE_ENCRYPTION) | ||
| } | ||
| } | ||
|
|
||
| private companion object { | ||
| // AES-GCM with a 96-bit nonce and a 128-bit tag, as the encryption design specifies. | ||
| const val AEAD_OVERHEAD_BYTES = 12 + 16 | ||
| } | ||
| } | ||
30 changes: 30 additions & 0 deletions
30
...ain/kotlin/team/cklob/mudda/domain/timecapsule/application/impl/CleanUpKeyShareService.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| package team.cklob.mudda.domain.timecapsule.application.impl | ||
|
|
||
| import org.slf4j.LoggerFactory | ||
| import org.springframework.scheduling.annotation.Scheduled | ||
| import org.springframework.stereotype.Service | ||
| import org.springframework.transaction.annotation.Transactional | ||
| import team.cklob.mudda.domain.timecapsule.domain.repository.KeyShareRepository | ||
| import java.time.LocalDateTime | ||
|
|
||
| // An expired capsule can never be opened again, so its key shares serve no purpose. Keeping them only | ||
| // leaves a wrapped share sitting in the database indefinitely, where an attacker who reaches the data can | ||
| // grind the lock secret offline for as long as they like. The encryption design calls for removing them | ||
| // on a schedule, and this is that job. | ||
| // | ||
| // Note this deletes only the shares, not the capsule row or its ciphertext: the capsule stays visible as | ||
| // an expired capsule, it simply becomes permanently unopenable, which is the intended end state. | ||
| @Service | ||
| class CleanUpKeyShareService( | ||
| private val keyShareRepository: KeyShareRepository, | ||
| ) { | ||
| private val logger = LoggerFactory.getLogger(javaClass) | ||
|
|
||
| @Scheduled(cron = "\${capsule.key-share-cleanup.cron:0 30 4 * * *}") | ||
| @Transactional | ||
| fun execute(): Int { | ||
| val deleted = keyShareRepository.deleteSharesOfCapsulesExpiredBefore(LocalDateTime.now()) | ||
| if (deleted > 0) logger.info("deleted {} key shares belonging to expired capsules", deleted) | ||
| return deleted | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
46 changes: 46 additions & 0 deletions
46
src/main/kotlin/team/cklob/mudda/domain/timecapsule/domain/entity/KeyShare.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| package team.cklob.mudda.domain.timecapsule.domain.entity | ||
|
|
||
| import jakarta.persistence.Column | ||
| import jakarta.persistence.Entity | ||
| import jakarta.persistence.FetchType | ||
| import jakarta.persistence.GeneratedValue | ||
| import jakarta.persistence.GenerationType | ||
| import jakarta.persistence.Id | ||
| import jakarta.persistence.JoinColumn | ||
| import jakarta.persistence.ManyToOne | ||
| import jakarta.persistence.Table | ||
| import jakarta.persistence.UniqueConstraint | ||
| import team.cklob.mudda.global.common.entity.BaseCreatedAtEntity | ||
|
|
||
| // One Shamir share of a CLIENT_E2E capsule's content key. | ||
| // | ||
| // The server deliberately holds fewer usable shares than the threshold. A wrapped share is stored as | ||
| // ciphertext under a key derived from the capsule's password or answer, which the server only knows as a | ||
| // bcrypt hash -- so it counts toward the client's quorum but never toward the server's. | ||
| @Entity | ||
| @Table( | ||
| name = "tbl_key_share", | ||
| uniqueConstraints = [ | ||
| UniqueConstraint(name = "uq_key_share_capsule_index", columnNames = ["time_capsule_id", "share_index"]), | ||
| ], | ||
| ) | ||
| class KeyShare( | ||
| @ManyToOne(fetch = FetchType.LAZY) | ||
| @JoinColumn(name = "time_capsule_id", nullable = false) | ||
| val timeCapsule: TimeCapsule, | ||
|
|
||
| // The Shamir x-coordinate. Interpolation cannot recover the key without it, so it travels with the | ||
| // share rather than being implied by row order. | ||
| @Column(name = "share_index", nullable = false) | ||
| val shareIndex: Int, | ||
|
|
||
| @Column(name = "share_data", nullable = false, columnDefinition = "TEXT") | ||
| val shareData: String, | ||
|
|
||
| @Column(name = "is_wrapped", nullable = false) | ||
| val isWrapped: Boolean, | ||
|
|
||
| @Id | ||
| @GeneratedValue(strategy = GenerationType.IDENTITY) | ||
| val id: Long? = null, | ||
| ) : BaseCreatedAtEntity() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.