1 // SPDX-License-Identifier: GPL-2.0
3 * The base64 encode/decode code was copied from fscrypt:
4 * Copyright (C) 2015, Google, Inc.
5 * Copyright (C) 2015, Motorola Mobility
6 * Written by Uday Savagaonkar, 2014.
7 * Modified by Jaegeuk Kim, 2015.
9 #include <linux/ceph/ceph_debug.h>
10 #include <linux/xattr.h>
11 #include <linux/fscrypt.h>
12 #include <linux/ceph/striper.h>
15 #include "mds_client.h"
19 * The base64url encoding used by fscrypt includes the '_' character, which may
20 * cause problems in snapshot names (which can not start with '_'). Thus, we
21 * used the base64 encoding defined for IMAP mailbox names (RFC 3501) instead,
22 * which replaces '-' and '_' by '+' and ','.
24 static const char base64_table[65] =
25 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,";
27 int ceph_base64_encode(const u8 *src, int srclen, char *dst)
34 for (i = 0; i < srclen; i++) {
35 ac = (ac << 8) | src[i];
39 *cp++ = base64_table[(ac >> bits) & 0x3f];
43 *cp++ = base64_table[(ac << (6 - bits)) & 0x3f];
47 int ceph_base64_decode(const char *src, int srclen, u8 *dst)
54 for (i = 0; i < srclen; i++) {
55 const char *p = strchr(base64_table, src[i]);
57 if (p == NULL || src[i] == 0)
59 ac = (ac << 6) | (p - base64_table);
63 *bp++ = (u8)(ac >> bits);
66 if (ac & ((1 << bits) - 1))
71 static int ceph_crypt_get_context(struct inode *inode, void *ctx, size_t len)
73 struct ceph_inode_info *ci = ceph_inode(inode);
74 struct ceph_fscrypt_auth *cfa = (struct ceph_fscrypt_auth *)ci->fscrypt_auth;
77 /* Non existent or too short? */
78 if (!cfa || (ci->fscrypt_auth_len < (offsetof(struct ceph_fscrypt_auth, cfa_blob) + 1)))
81 /* Some format we don't recognize? */
82 if (le32_to_cpu(cfa->cfa_version) != CEPH_FSCRYPT_AUTH_VERSION)
85 ctxlen = le32_to_cpu(cfa->cfa_blob_len);
89 memcpy(ctx, cfa->cfa_blob, ctxlen);
93 static int ceph_crypt_set_context(struct inode *inode, const void *ctx,
94 size_t len, void *fs_data)
97 struct iattr attr = { };
98 struct ceph_iattr cia = { };
99 struct ceph_fscrypt_auth *cfa;
101 WARN_ON_ONCE(fs_data);
103 if (len > FSCRYPT_SET_CONTEXT_MAX_SIZE)
106 cfa = kzalloc(sizeof(*cfa), GFP_KERNEL);
110 cfa->cfa_version = cpu_to_le32(CEPH_FSCRYPT_AUTH_VERSION);
111 cfa->cfa_blob_len = cpu_to_le32(len);
112 memcpy(cfa->cfa_blob, ctx, len);
114 cia.fscrypt_auth = cfa;
116 ret = __ceph_setattr(inode, &attr, &cia);
118 inode_set_flags(inode, S_ENCRYPTED, S_ENCRYPTED);
119 kfree(cia.fscrypt_auth);
123 static bool ceph_crypt_empty_dir(struct inode *inode)
125 struct ceph_inode_info *ci = ceph_inode(inode);
127 return ci->i_rsubdirs + ci->i_rfiles == 1;
130 static const union fscrypt_policy *ceph_get_dummy_policy(struct super_block *sb)
132 return ceph_sb_to_client(sb)->fsc_dummy_enc_policy.policy;
135 static struct fscrypt_operations ceph_fscrypt_ops = {
136 .get_context = ceph_crypt_get_context,
137 .set_context = ceph_crypt_set_context,
138 .get_dummy_policy = ceph_get_dummy_policy,
139 .empty_dir = ceph_crypt_empty_dir,
142 void ceph_fscrypt_set_ops(struct super_block *sb)
144 fscrypt_set_ops(sb, &ceph_fscrypt_ops);
147 void ceph_fscrypt_free_dummy_policy(struct ceph_fs_client *fsc)
149 fscrypt_free_dummy_policy(&fsc->fsc_dummy_enc_policy);
152 int ceph_fscrypt_prepare_context(struct inode *dir, struct inode *inode,
153 struct ceph_acl_sec_ctx *as)
156 bool encrypted = false;
157 struct ceph_inode_info *ci = ceph_inode(inode);
159 ret = fscrypt_prepare_new_inode(dir, inode, &encrypted);
165 as->fscrypt_auth = kzalloc(sizeof(*as->fscrypt_auth), GFP_KERNEL);
166 if (!as->fscrypt_auth)
169 ctxsize = fscrypt_context_for_new_inode(as->fscrypt_auth->cfa_blob,
174 as->fscrypt_auth->cfa_version = cpu_to_le32(CEPH_FSCRYPT_AUTH_VERSION);
175 as->fscrypt_auth->cfa_blob_len = cpu_to_le32(ctxsize);
177 WARN_ON_ONCE(ci->fscrypt_auth);
178 kfree(ci->fscrypt_auth);
179 ci->fscrypt_auth_len = ceph_fscrypt_auth_len(as->fscrypt_auth);
180 ci->fscrypt_auth = kmemdup(as->fscrypt_auth, ci->fscrypt_auth_len,
182 if (!ci->fscrypt_auth)
185 inode->i_flags |= S_ENCRYPTED;
190 void ceph_fscrypt_as_ctx_to_req(struct ceph_mds_request *req,
191 struct ceph_acl_sec_ctx *as)
193 swap(req->r_fscrypt_auth, as->fscrypt_auth);
197 * User-created snapshots can't start with '_'. Snapshots that start with this
198 * character are special (hint: there aren't real snapshots) and use the
201 * _<SNAPSHOT-NAME>_<INODE-NUMBER>
204 * - <SNAPSHOT-NAME> - the real snapshot name that may need to be decrypted,
205 * - <INODE-NUMBER> - the inode number (in decimal) for the actual snapshot
207 * This function parses these snapshot names and returns the inode
208 * <INODE-NUMBER>. 'name_len' will also bet set with the <SNAPSHOT-NAME>
211 static struct inode *parse_longname(const struct inode *parent,
212 const char *name, int *name_len)
214 struct inode *dir = NULL;
215 struct ceph_vino vino = { .snap = CEPH_NOSNAP };
218 int orig_len = *name_len;
221 /* Skip initial '_' */
223 name_end = strrchr(name, '_');
225 dout("Failed to parse long snapshot name: %s\n", name);
226 return ERR_PTR(-EIO);
228 *name_len = (name_end - name);
229 if (*name_len <= 0) {
230 pr_err("Failed to parse long snapshot name\n");
231 return ERR_PTR(-EIO);
234 /* Get the inode number */
235 inode_number = kmemdup_nul(name_end + 1,
236 orig_len - *name_len - 2,
239 return ERR_PTR(-ENOMEM);
240 ret = kstrtou64(inode_number, 10, &vino.ino);
242 dout("Failed to parse inode number: %s\n", name);
247 /* And finally the inode */
248 dir = ceph_find_inode(parent->i_sb, vino);
250 /* This can happen if we're not mounting cephfs on the root */
251 dir = ceph_get_inode(parent->i_sb, vino, NULL);
253 dout("Can't find inode %s (%s)\n", inode_number, name);
261 int ceph_encode_encrypted_dname(struct inode *parent, struct qstr *d_name,
264 struct inode *dir = parent;
272 iname.name = d_name->name;
273 name_len = d_name->len;
275 /* Handle the special case of snapshot names that start with '_' */
276 if ((ceph_snap(dir) == CEPH_SNAPDIR) && (name_len > 0) &&
277 (iname.name[0] == '_')) {
278 dir = parse_longname(parent, iname.name, &name_len);
281 iname.name++; /* skip initial '_' */
283 iname.len = name_len;
285 if (!fscrypt_has_encryption_key(dir)) {
286 memcpy(buf, d_name->name, d_name->len);
292 * Convert cleartext d_name to ciphertext. If result is longer than
293 * CEPH_NOHASH_NAME_MAX, sha256 the remaining bytes
295 * See: fscrypt_setup_filename
297 if (!fscrypt_fname_encrypted_size(dir, iname.len, NAME_MAX, &len)) {
298 elen = -ENAMETOOLONG;
302 /* Allocate a buffer appropriate to hold the result */
303 cryptbuf = kmalloc(len > CEPH_NOHASH_NAME_MAX ? NAME_MAX : len,
310 ret = fscrypt_fname_encrypt(dir, &iname, cryptbuf, len);
316 /* hash the end if the name is long enough */
317 if (len > CEPH_NOHASH_NAME_MAX) {
318 u8 hash[SHA256_DIGEST_SIZE];
319 u8 *extra = cryptbuf + CEPH_NOHASH_NAME_MAX;
322 * hash the extra bytes and overwrite crypttext beyond that
325 sha256(extra, len - CEPH_NOHASH_NAME_MAX, hash);
326 memcpy(extra, hash, SHA256_DIGEST_SIZE);
327 len = CEPH_NOHASH_NAME_MAX + SHA256_DIGEST_SIZE;
330 /* base64 encode the encrypted name */
331 elen = ceph_base64_encode(cryptbuf, len, buf);
332 dout("base64-encoded ciphertext name = %.*s\n", elen, buf);
334 /* To understand the 240 limit, see CEPH_NOHASH_NAME_MAX comments */
336 if ((elen > 0) && (dir != parent)) {
337 char tmp_buf[NAME_MAX];
339 elen = snprintf(tmp_buf, sizeof(tmp_buf), "_%.*s_%ld",
340 elen, buf, dir->i_ino);
341 memcpy(buf, tmp_buf, elen);
347 if ((dir->i_state & I_NEW))
348 discard_new_inode(dir);
355 int ceph_encode_encrypted_fname(struct inode *parent, struct dentry *dentry,
358 WARN_ON_ONCE(!fscrypt_has_encryption_key(parent));
360 return ceph_encode_encrypted_dname(parent, &dentry->d_name, buf);
364 * ceph_fname_to_usr - convert a filename for userland presentation
365 * @fname: ceph_fname to be converted
366 * @tname: temporary name buffer to use for conversion (may be NULL)
367 * @oname: where converted name should be placed
368 * @is_nokey: set to true if key wasn't available during conversion (may be NULL)
370 * Given a filename (usually from the MDS), format it for presentation to
371 * userland. If @parent is not encrypted, just pass it back as-is.
373 * Otherwise, base64 decode the string, and then ask fscrypt to format it
374 * for userland presentation.
376 * Returns 0 on success or negative error code on error.
378 int ceph_fname_to_usr(const struct ceph_fname *fname, struct fscrypt_str *tname,
379 struct fscrypt_str *oname, bool *is_nokey)
381 struct inode *dir = fname->dir;
382 struct fscrypt_str _tname = FSTR_INIT(NULL, 0);
383 struct fscrypt_str iname;
384 char *name = fname->name;
385 int name_len = fname->name_len;
388 /* Sanity check that the resulting name will fit in the buffer */
389 if (fname->name_len > NAME_MAX || fname->ctext_len > NAME_MAX)
392 /* Handle the special case of snapshot names that start with '_' */
393 if ((ceph_snap(dir) == CEPH_SNAPDIR) && (name_len > 0) &&
395 dir = parse_longname(dir, name, &name_len);
398 name++; /* skip initial '_' */
401 if (!IS_ENCRYPTED(dir)) {
402 oname->name = fname->name;
403 oname->len = fname->name_len;
408 ret = ceph_fscrypt_prepare_readdir(dir);
413 * Use the raw dentry name as sent by the MDS instead of
414 * generating a nokey name via fscrypt.
416 if (!fscrypt_has_encryption_key(dir)) {
418 oname->name = fname->name;
420 memcpy(oname->name, fname->name, fname->name_len);
421 oname->len = fname->name_len;
428 if (fname->ctext_len == 0) {
432 ret = fscrypt_fname_alloc_buffer(NAME_MAX, &_tname);
438 declen = ceph_base64_decode(name, name_len, tname->name);
443 iname.name = tname->name;
446 iname.name = fname->ctext;
447 iname.len = fname->ctext_len;
450 ret = fscrypt_fname_disk_to_usr(dir, 0, 0, &iname, oname);
451 if (!ret && (dir != fname->dir)) {
452 char tmp_buf[CEPH_BASE64_CHARS(NAME_MAX)];
454 name_len = snprintf(tmp_buf, sizeof(tmp_buf), "_%.*s_%ld",
455 oname->len, oname->name, dir->i_ino);
456 memcpy(oname->name, tmp_buf, name_len);
457 oname->len = name_len;
461 fscrypt_fname_free_buffer(&_tname);
463 if (dir != fname->dir) {
464 if ((dir->i_state & I_NEW))
465 discard_new_inode(dir);
473 * ceph_fscrypt_prepare_readdir - simple __fscrypt_prepare_readdir() wrapper
474 * @dir: directory inode for readdir prep
476 * Simple wrapper around __fscrypt_prepare_readdir() that will mark directory as
477 * non-complete if this call results in having the directory unlocked.
480 * 1 - if directory was locked and key is now loaded (i.e. dir is unlocked)
481 * 0 - if directory is still locked
482 * < 0 - if __fscrypt_prepare_readdir() fails
484 int ceph_fscrypt_prepare_readdir(struct inode *dir)
486 bool had_key = fscrypt_has_encryption_key(dir);
489 if (!IS_ENCRYPTED(dir))
492 err = __fscrypt_prepare_readdir(dir);
495 if (!had_key && fscrypt_has_encryption_key(dir)) {
496 /* directory just got unlocked, mark it as not complete */
497 ceph_dir_clear_complete(dir);
503 int ceph_fscrypt_decrypt_block_inplace(const struct inode *inode,
504 struct page *page, unsigned int len,
505 unsigned int offs, u64 lblk_num)
507 dout("%s: len %u offs %u blk %llu\n", __func__, len, offs, lblk_num);
508 return fscrypt_decrypt_block_inplace(inode, page, len, offs, lblk_num);
511 int ceph_fscrypt_encrypt_block_inplace(const struct inode *inode,
512 struct page *page, unsigned int len,
513 unsigned int offs, u64 lblk_num,
516 dout("%s: len %u offs %u blk %llu\n", __func__, len, offs, lblk_num);
517 return fscrypt_encrypt_block_inplace(inode, page, len, offs, lblk_num,
522 * ceph_fscrypt_decrypt_pages - decrypt an array of pages
523 * @inode: pointer to inode associated with these pages
524 * @page: pointer to page array
525 * @off: offset into the file that the read data starts
526 * @len: max length to decrypt
528 * Decrypt an array of fscrypt'ed pages and return the amount of
529 * data decrypted. Any data in the page prior to the start of the
530 * first complete block in the read is ignored. Any incomplete
531 * crypto blocks at the end of the array are ignored (and should
532 * probably be zeroed by the caller).
534 * Returns the length of the decrypted data or a negative errno.
536 int ceph_fscrypt_decrypt_pages(struct inode *inode, struct page **page,
540 u64 baseblk = off >> CEPH_FSCRYPT_BLOCK_SHIFT;
544 * We can't deal with partial blocks on an encrypted file, so mask off
547 num_blocks = ceph_fscrypt_blocks(off, len & CEPH_FSCRYPT_BLOCK_MASK);
549 /* Decrypt each block */
550 for (i = 0; i < num_blocks; ++i) {
551 int blkoff = i << CEPH_FSCRYPT_BLOCK_SHIFT;
552 int pgidx = blkoff >> PAGE_SHIFT;
553 unsigned int pgoffs = offset_in_page(blkoff);
556 fret = ceph_fscrypt_decrypt_block_inplace(inode, page[pgidx],
557 CEPH_FSCRYPT_BLOCK_SIZE, pgoffs,
564 ret += CEPH_FSCRYPT_BLOCK_SIZE;
570 * ceph_fscrypt_decrypt_extents: decrypt received extents in given buffer
571 * @inode: inode associated with pages being decrypted
572 * @page: pointer to page array
573 * @off: offset into the file that the data in page[0] starts
574 * @map: pointer to extent array
575 * @ext_cnt: length of extent array
577 * Given an extent map and a page array, decrypt the received data in-place,
578 * skipping holes. Returns the offset into buffer of end of last decrypted
581 int ceph_fscrypt_decrypt_extents(struct inode *inode, struct page **page,
582 u64 off, struct ceph_sparse_extent *map,
586 struct ceph_inode_info *ci = ceph_inode(inode);
590 /* Nothing to do for empty array */
592 dout("%s: empty array, ret 0\n", __func__);
596 ceph_calc_file_object_mapping(&ci->i_layout, off, map[0].len,
597 &objno, &objoff, &xlen);
599 for (i = 0; i < ext_cnt; ++i) {
600 struct ceph_sparse_extent *ext = &map[i];
601 int pgsoff = ext->off - objoff;
602 int pgidx = pgsoff >> PAGE_SHIFT;
605 if ((ext->off | ext->len) & ~CEPH_FSCRYPT_BLOCK_MASK) {
606 pr_warn("%s: bad encrypted sparse extent idx %d off %llx len %llx\n",
607 __func__, i, ext->off, ext->len);
610 fret = ceph_fscrypt_decrypt_pages(inode, &page[pgidx],
611 off + pgsoff, ext->len);
612 dout("%s: [%d] 0x%llx~0x%llx fret %d\n", __func__, i,
613 ext->off, ext->len, fret);
621 dout("%s: ret %d\n", __func__, ret);
626 * ceph_fscrypt_encrypt_pages - encrypt an array of pages
627 * @inode: pointer to inode associated with these pages
628 * @page: pointer to page array
629 * @off: offset into the file that the data starts
630 * @len: max length to encrypt
631 * @gfp: gfp flags to use for allocation
633 * Decrypt an array of cleartext pages and return the amount of
634 * data encrypted. Any data in the page prior to the start of the
635 * first complete block in the read is ignored. Any incomplete
636 * crypto blocks at the end of the array are ignored.
638 * Returns the length of the encrypted data or a negative errno.
640 int ceph_fscrypt_encrypt_pages(struct inode *inode, struct page **page, u64 off,
644 u64 baseblk = off >> CEPH_FSCRYPT_BLOCK_SHIFT;
648 * We can't deal with partial blocks on an encrypted file, so mask off
651 num_blocks = ceph_fscrypt_blocks(off, len & CEPH_FSCRYPT_BLOCK_MASK);
653 /* Encrypt each block */
654 for (i = 0; i < num_blocks; ++i) {
655 int blkoff = i << CEPH_FSCRYPT_BLOCK_SHIFT;
656 int pgidx = blkoff >> PAGE_SHIFT;
657 unsigned int pgoffs = offset_in_page(blkoff);
660 fret = ceph_fscrypt_encrypt_block_inplace(inode, page[pgidx],
661 CEPH_FSCRYPT_BLOCK_SIZE, pgoffs,
668 ret += CEPH_FSCRYPT_BLOCK_SIZE;