summaryrefslogtreecommitdiff
path: root/crates/jmap/src/api/management/dkim.rs
blob: 5d00e30fd47ce4b40d4e3dc8af1694c6ac58f907 (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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
/*
 * Copyright (c) 2023 Stalwart Labs Ltd.
 *
 * This file is part of Stalwart Mail Server.
 *
 * This program 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 of
 * the License, or (at your option) any later version.
 *
 * This program 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.
 * in the LICENSE file at the top-level directory of this distribution.
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * You can be released from the requirements of the AGPLv3 license by
 * purchasing a commercial license. Please contact licensing@stalw.art
 * for more details.
*/

use std::str::FromStr;

use common::config::smtp::auth::simple_pem_parse;
use hyper::Method;
use jmap_proto::error::request::RequestError;
use mail_auth::{
    common::crypto::{Ed25519Key, RsaKey, Sha256},
    dkim::generate::DkimKeyPair,
};
use mail_builder::encoders::base64::base64_encode;
use mail_parser::DateTime;
use pkcs8::Document;
use rsa::pkcs1::DecodeRsaPublicKey;
use serde::{Deserialize, Serialize};
use serde_json::json;
use store::write::now;

use crate::{
    api::{
        http::ToHttpResponse, management::ManagementApiError, HttpRequest, HttpResponse,
        JsonResponse,
    },
    JMAP,
};

use super::decode_path_element;

#[derive(Debug, Serialize, Deserialize, Copy, Clone, PartialEq, Eq)]
pub enum Algorithm {
    Rsa,
    Ed25519,
}

#[derive(Debug, Serialize, Deserialize)]
struct DkimSignature {
    id: Option<String>,
    algorithm: Algorithm,
    domain: String,
    selector: Option<String>,
}

impl JMAP {
    pub async fn handle_manage_dkim(
        &self,
        req: &HttpRequest,
        path: Vec<&str>,
        body: Option<Vec<u8>>,
    ) -> HttpResponse {
        match *req.method() {
            Method::GET => self.handle_get_public_key(path).await,
            Method::POST => self.handle_create_signature(body).await,
            _ => RequestError::not_found().into_http_response(),
        }
    }

    async fn handle_get_public_key(&self, path: Vec<&str>) -> HttpResponse {
        let signature_id = match path.get(1) {
            Some(signature_id) => decode_path_element(signature_id),
            None => {
                return RequestError::not_found().into_http_response();
            }
        };

        let (pk, algo) = match (
            self.core
                .storage
                .config
                .get(&format!("signature.{signature_id}.private-key"))
                .await,
            self.core
                .storage
                .config
                .get(&format!("signature.{signature_id}.algorithm"))
                .await
                .map(|algo| algo.and_then(|algo| algo.parse::<Algorithm>().ok())),
        ) {
            (Ok(Some(pk)), Ok(Some(algorithm))) => (pk, algorithm),
            (Err(err), _) | (_, Err(err)) => return err.into_http_response(),
            _ => return RequestError::not_found().into_http_response(),
        };

        match obtain_dkim_public_key(algo, &pk) {
            Ok(data) => JsonResponse::new(json!({
                "data": data,
            }))
            .into_http_response(),
            Err(err) => ManagementApiError::Other {
                details: err.into(),
            }
            .into_http_response(),
        }
    }

    async fn handle_create_signature(&self, body: Option<Vec<u8>>) -> HttpResponse {
        let request =
            match serde_json::from_slice::<DkimSignature>(body.as_deref().unwrap_or_default()) {
                Ok(request) => request,
                Err(err) => return err.into_http_response(),
            };

        let algo_str = match request.algorithm {
            Algorithm::Rsa => "rsa",
            Algorithm::Ed25519 => "ed25519",
        };
        let id = request
            .id
            .unwrap_or_else(|| format!("{algo_str}-{}", request.domain));
        let selector = request.selector.unwrap_or_else(|| {
            let dt = DateTime::from_timestamp(now() as i64);
            format!(
                "{:04}{:02}{}",
                dt.year,
                dt.month,
                if Algorithm::Rsa == request.algorithm {
                    "r"
                } else {
                    "e"
                }
            )
        });

        // Make sure the signature does not exist already
        match self
            .core
            .storage
            .config
            .get(&format!("signature.{id}.private-key"))
            .await
        {
            Ok(None) => (),
            Ok(Some(value)) => {
                return ManagementApiError::FieldAlreadyExists {
                    field: format!("signature.{id}.private-key").into(),
                    value: value.into(),
                }
                .into_http_response();
            }
            Err(err) => return err.into_http_response(),
        }

        // Create signature
        match self
            .create_dkim_key(request.algorithm, id, request.domain, selector)
            .await
        {
            Ok(_) => JsonResponse::new(json!({
                "data": (),
            }))
            .into_http_response(),
            Err(err) => err.into_http_response(),
        }
    }

    async fn create_dkim_key(
        &self,
        algo: Algorithm,
        id: impl AsRef<str>,
        domain: impl Into<String>,
        selector: impl Into<String>,
    ) -> store::Result<()> {
        let id = id.as_ref();
        let (algorithm, pk_type) = match algo {
            Algorithm::Rsa => ("rsa-sha256", "RSA PRIVATE KEY"),
            Algorithm::Ed25519 => ("ed25519-sha256", "PRIVATE KEY"),
        };
        let mut pk = format!("-----BEGIN {pk_type}-----\n").into_bytes();
        let mut lf_count = 65;
        for ch in base64_encode(
            match algo {
                Algorithm::Rsa => DkimKeyPair::generate_rsa(2048),
                Algorithm::Ed25519 => DkimKeyPair::generate_ed25519(),
            }
            .map_err(|err| store::Error::InternalError(err.to_string()))?
            .private_key(),
        )
        .unwrap_or_default()
        {
            pk.push(ch);
            lf_count -= 1;
            if lf_count == 0 {
                pk.push(b'\n');
                lf_count = 65;
            }
        }
        if lf_count != 65 {
            pk.push(b'\n');
        }
        pk.extend_from_slice(format!("-----END {pk_type}-----\n").as_bytes());

        self.core
            .storage
            .config
            .set([
                (
                    format!("signature.{id}.private-key"),
                    String::from_utf8(pk).unwrap(),
                ),
                (format!("signature.{id}.domain"), domain.into()),
                (format!("signature.{id}.selector"), selector.into()),
                (format!("signature.{id}.algorithm"), algorithm.to_string()),
                (
                    format!("signature.{id}.canonicalization"),
                    "relaxed/relaxed".to_string(),
                ),
                (format!("signature.{id}.headers.0"), "From".to_string()),
                (format!("signature.{id}.headers.1"), "To".to_string()),
                (format!("signature.{id}.headers.2"), "Date".to_string()),
                (format!("signature.{id}.headers.3"), "Subject".to_string()),
                (
                    format!("signature.{id}.headers.4"),
                    "Message-ID".to_string(),
                ),
                (format!("signature.{id}.report"), "false".to_string()),
            ])
            .await
    }
}

pub fn obtain_dkim_public_key(algo: Algorithm, pk: &str) -> Result<String, &'static str> {
    match simple_pem_parse(pk) {
        Some(der) => match algo {
            Algorithm::Rsa => match RsaKey::<Sha256>::from_der(&der).and_then(|key| {
                Document::from_pkcs1_der(&key.public_key())
                    .map_err(|err| mail_auth::Error::CryptoError(err.to_string()))
            }) {
                Ok(pk) => Ok(
                    String::from_utf8(base64_encode(pk.as_bytes()).unwrap_or_default())
                        .unwrap_or_default(),
                ),
                Err(err) => {
                    tracing::debug!("Failed to read RSA DER: {err}");

                    Err("Failed to read RSA DER")
                }
            },
            Algorithm::Ed25519 => {
                match Ed25519Key::from_pkcs8_maybe_unchecked_der(&der)
                    .map_err(|err| mail_auth::Error::CryptoError(err.to_string()))
                {
                    Ok(pk) => Ok(String::from_utf8(
                        base64_encode(&pk.public_key()).unwrap_or_default(),
                    )
                    .unwrap_or_default()),
                    Err(err) => {
                        tracing::debug!("Failed to read ED25519 DER: {err}");

                        Err("Failed to read ED25519 DER")
                    }
                }
            }
        },
        None => Err("Failed to decode private key"),
    }
}

impl FromStr for Algorithm {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.split_once('-').map(|(algo, _)| algo) {
            Some("rsa") => Ok(Algorithm::Rsa),
            Some("ed25519") => Ok(Algorithm::Ed25519),
            _ => Err(()),
        }
    }
}