summaryrefslogtreecommitdiff
path: root/nexus/src/main/kotlin/tech/libeufin/nexus/KeyFiles.kt
blob: fd91cfd48249c64ccd3f990302f2fa08cad00e6a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
/*
 * This file is part of LibEuFin.
 * Copyright (C) 2023 Stanisci and Dold.

 * LibEuFin is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation; either version 3, or
 * (at your option) any later version.

 * LibEuFin is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General
 * Public License for more details.

 * You should have received a copy of the GNU Affero General Public
 * License along with LibEuFin; see the file COPYING.  If not, see
 * <http://www.gnu.org/licenses/>
 */

package tech.libeufin.nexus

import kotlinx.serialization.Contextual
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encodeToString
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.Json
import kotlinx.serialization.modules.SerializersModule
import tech.libeufin.common.Base32Crockford
import tech.libeufin.common.crypto.CryptoUtil
import java.nio.file.*
import java.security.interfaces.RSAPrivateCrtKey
import java.security.interfaces.RSAPublicKey
import kotlin.io.path.*

val JSON = Json {
    this.serializersModule = SerializersModule {
        contextual(RSAPrivateCrtKey::class) { RSAPrivateCrtKeySerializer }
        contextual(RSAPublicKey::class) { RSAPublicKeySerializer }
    }
}

/**
 * Converts base 32 representation of RSA public keys and vice versa.
 */
object RSAPublicKeySerializer : KSerializer<RSAPublicKey> {
    override val descriptor: SerialDescriptor =
        PrimitiveSerialDescriptor("RSAPublicKey", PrimitiveKind.STRING)
    override fun serialize(encoder: Encoder, value: RSAPublicKey) {
        encoder.encodeString(Base32Crockford.encode(value.encoded))
    }

    // Caller must handle exceptions here.
    override fun deserialize(decoder: Decoder): RSAPublicKey {
        val fieldValue = decoder.decodeString()
        val bytes = Base32Crockford.decode(fieldValue)
        return CryptoUtil.loadRsaPublicKey(bytes)
    }
}

/**
 * Converts base 32 representation of RSA private keys and vice versa.
 */
object RSAPrivateCrtKeySerializer : KSerializer<RSAPrivateCrtKey> {
    override val descriptor: SerialDescriptor =
        PrimitiveSerialDescriptor("RSAPrivateCrtKey", PrimitiveKind.STRING)
    override fun serialize(encoder: Encoder, value: RSAPrivateCrtKey) {
        encoder.encodeString(Base32Crockford.encode(value.encoded))
    }

    // Caller must handle exceptions here.
    override fun deserialize(decoder: Decoder): RSAPrivateCrtKey {
        val fieldValue = decoder.decodeString()
        val bytes = Base32Crockford.decode(fieldValue)
        return CryptoUtil.loadRsaPrivateKey(bytes)
    }
}

/**
 * Structure of the JSON file that contains the client
 * private keys on disk.
 */
@Serializable
data class ClientPrivateKeysFile(
    @Contextual val signature_private_key: RSAPrivateCrtKey,
    @Contextual val encryption_private_key: RSAPrivateCrtKey,
    @Contextual val authentication_private_key: RSAPrivateCrtKey,
    var submitted_ini: Boolean,
    var submitted_hia: Boolean
)

/**
 * Structure of the JSON file that contains the bank
 * public keys on disk.
 */
@Serializable
data class BankPublicKeysFile(
    @Contextual val bank_encryption_public_key: RSAPublicKey,
    @Contextual val bank_authentication_public_key: RSAPublicKey,
    var accepted: Boolean
)

/**
 * Generates new client private keys.
 *
 * @return [ClientPrivateKeysFile]
 */
fun generateNewKeys(): ClientPrivateKeysFile =
    ClientPrivateKeysFile(
        authentication_private_key = CryptoUtil.generateRsaKeyPair(2048).private,
        encryption_private_key = CryptoUtil.generateRsaKeyPair(2048).private,
        signature_private_key = CryptoUtil.generateRsaKeyPair(2048).private,
        submitted_hia = false,
        submitted_ini = false
    )

private inline fun <reified T> persistJsonFile(obj: T, path: Path, name: String) {
    val content = try {
        JSON.encodeToString(obj)
    } catch (e: Exception) {
        throw Exception("Could not encode $name", e)
    }
    val parent = try {
        path.parent ?: path.absolute().parent
    } catch (e: Exception) {
        throw Exception("Could not write $name at '$path'", e)
    }
    try {
        // Write to temp file then rename to enable atomicity when possible
        val tmp = Files.createTempFile(parent, "tmp_", "_${path.fileName}")
        tmp.writeText(content)
        tmp.moveTo(path, StandardCopyOption.REPLACE_EXISTING)
    } catch (e: Exception) {
        when {
            !parent.isWritable() -> throw Exception("Could not write $name at '$path': permission denied on '$parent'")
            !path.isWritable() -> throw Exception("Could not write $name at '$path': permission denied")
            else -> throw Exception("Could not write $name at '$path'", e)
        }
    }
}

/**
 * Persist the bank keys file to disk
 *
 * @param location the keys file location
 */
fun persistBankKeys(keys: BankPublicKeysFile, location: Path) = persistJsonFile(keys, location, "bank public keys")

/**
 * Persist the client keys file to disk
 *
 * @param location the keys file location
 */
fun persistClientKeys(keys: ClientPrivateKeysFile, location: Path) = persistJsonFile(keys, location, "client private keys")


private inline fun <reified T> loadJsonFile(path: Path, name: String): T? {
    val content = try {
        path.readText()
    } catch (e: Exception) {
        when (e) {
            is NoSuchFileException -> return null
            is AccessDeniedException -> throw Exception("Could not read $name at '$path': permission denied")
            else -> throw Exception("Could not read $name at '$path'", e)
        }
    }
    return try {
        JSON.decodeFromString(content)
    } catch (e: Exception) {
        throw Exception("Could not decode $name at '$path'", e)
    }
}

/**
 * Load the bank keys file from disk.
 *
 * @param location the keys file location.
 * @return the internal JSON representation of the keys file,
 *         or null if the file does not exist
 */
fun loadBankKeys(location: Path): BankPublicKeysFile? = loadJsonFile(location, "bank public keys")

/**
 * Load the client keys file from disk.
 *
 * @param location the keys file location.
 * @return the internal JSON representation of the keys file,
 *         or null if the file does not exist
 */
fun loadClientKeys(location: Path): ClientPrivateKeysFile? = loadJsonFile(location, "client private keys")

/**
 * Load client and bank keys from disk.
 * Checks that the keying process has been fully completed.
 * 
 * Helps to fail before starting to talk EBICS to the bank.
 *
 * @param cfg configuration handle.
 * @return both client and bank keys
 */
fun expectFullKeys(
    cfg: EbicsSetupConfig
): Pair<ClientPrivateKeysFile, BankPublicKeysFile> {
    val clientKeys = loadClientKeys(cfg.clientPrivateKeysFilename)
    if (clientKeys == null) {
        throw Exception("Missing client private keys file at '${cfg.clientPrivateKeysFilename}', run 'libeufin-nexus ebics-setup' first")
    } else if (!clientKeys.submitted_ini || !clientKeys.submitted_hia) {
        throw Exception("Unsubmitted client private keys, run 'libeufin-nexus ebics-setup' first")
    }
    val bankKeys = loadBankKeys(cfg.bankPublicKeysFilename)
    if (bankKeys == null) {
        throw Exception("Missing bank public keys at '${cfg.bankPublicKeysFilename}', run 'libeufin-nexus ebics-setup' first")
    } else if (!bankKeys.accepted) {
        throw Exception("Unaccepted bank public keys, run 'libeufin-nexus ebics-setup' until accepting the bank keys")
    }
    return Pair(clientKeys, bankKeys)
}