-
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 4 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
61 changes: 61 additions & 0 deletions
61
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,61 @@ | ||
| package team.cklob.mudda.domain.timecapsule.application | ||
|
|
||
| import org.springframework.stereotype.Component | ||
| 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.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) { | ||
| when (mode) { | ||
| CapsuleEncryptionMode.SERVER_ENVELOPE -> validateServerEnvelope(request) | ||
| CapsuleEncryptionMode.CLIENT_E2E -> validateClientE2e(request) | ||
| } | ||
| } | ||
|
|
||
| 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) | ||
| } | ||
| } | ||
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() |
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
25 changes: 25 additions & 0 deletions
25
src/main/kotlin/team/cklob/mudda/domain/timecapsule/domain/repository/KeyShareRepository.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,25 @@ | ||
| package team.cklob.mudda.domain.timecapsule.domain.repository | ||
|
|
||
| import org.springframework.data.jpa.repository.JpaRepository | ||
| import org.springframework.data.jpa.repository.Modifying | ||
| import org.springframework.data.jpa.repository.Query | ||
| import org.springframework.data.repository.query.Param | ||
| import team.cklob.mudda.domain.timecapsule.domain.entity.KeyShare | ||
| import java.time.LocalDateTime | ||
|
|
||
| interface KeyShareRepository : JpaRepository<KeyShare, Long> { | ||
| fun findAllByTimeCapsuleIdOrderByShareIndex(timeCapsuleId: Long): List<KeyShare> | ||
|
|
||
| // An expired capsule can never be opened again, so its shares are dead weight that would only widen | ||
| // the window for an offline attack on a wrapped share. The encryption design calls for removing them | ||
| // on a schedule. | ||
| @Modifying(clearAutomatically = true, flushAutomatically = true) | ||
| @Query( | ||
| """ | ||
| DELETE FROM KeyShare k WHERE k.timeCapsule.id IN ( | ||
| SELECT c.id FROM TimeCapsule c WHERE c.expiredAt IS NOT NULL AND c.expiredAt <= :now | ||
| ) | ||
| """, | ||
| ) | ||
| fun deleteSharesOfCapsulesExpiredBefore(@Param("now") now: LocalDateTime): Int | ||
| } |
15 changes: 15 additions & 0 deletions
15
src/main/kotlin/team/cklob/mudda/domain/timecapsule/domain/type/CapsuleEncryptionMode.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,15 @@ | ||
| package team.cklob.mudda.domain.timecapsule.domain.type | ||
|
|
||
| // Which side holds the key to a capsule's body. | ||
| enum class CapsuleEncryptionMode { | ||
| // The server encrypts and decrypts the body with its own master key, so it can read the plaintext. | ||
| // Used for lockType = NONE, where end-to-end encryption is impossible by construction: the only | ||
| // unlock condition is being at the capsule's coordinates, and the server stores those coordinates, | ||
| // so any secret it could withhold from itself it could also re-derive. | ||
| SERVER_ENVELOPE, | ||
|
|
||
| // The client encrypts the body under a key the server never sees. The server keeps an opaque blob plus | ||
| // fewer key shares than the reconstruction threshold, so it cannot recover the body on its own. | ||
| // Requires a lock (PASSWORD or QUESTION): the lock secret is the one input the server does not hold. | ||
| CLIENT_E2E, | ||
| } |
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
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.