1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * net/tipc/crypto.c: TIPC crypto for key handling & packet en/decryption
4 *
5 * Copyright (c) 2019, Ericsson AB
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are met:
10 *
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the names of the copyright holders nor the names of its
17 * contributors may be used to endorse or promote products derived from
18 * this software without specific prior written permission.
19 *
20 * Alternatively, this software may be distributed under the terms of the
21 * GNU General Public License ("GPL") version 2 as published by the Free
22 * Software Foundation.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
25 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
29 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
30 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
32 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
33 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34 * POSSIBILITY OF SUCH DAMAGE.
35 */
36
37 #include <crypto/aead.h>
38 #include <crypto/aes.h>
39 #include <crypto/rng.h>
40 #include "crypto.h"
41 #include "msg.h"
42 #include "bcast.h"
43
44 #define TIPC_TX_GRACE_PERIOD msecs_to_jiffies(5000) /* 5s */
45 #define TIPC_TX_LASTING_TIME msecs_to_jiffies(10000) /* 10s */
46 #define TIPC_RX_ACTIVE_LIM msecs_to_jiffies(3000) /* 3s */
47 #define TIPC_RX_PASSIVE_LIM msecs_to_jiffies(15000) /* 15s */
48
49 #define TIPC_MAX_TFMS_DEF 10
50 #define TIPC_MAX_TFMS_LIM 1000
51
52 #define TIPC_REKEYING_INTV_DEF (60 * 24) /* default: 1 day */
53
54 /*
55 * TIPC Key ids
56 */
57 enum {
58 KEY_MASTER = 0,
59 KEY_MIN = KEY_MASTER,
60 KEY_1 = 1,
61 KEY_2,
62 KEY_3,
63 KEY_MAX = KEY_3,
64 };
65
66 /*
67 * TIPC Crypto statistics
68 */
69 enum {
70 STAT_OK,
71 STAT_NOK,
72 STAT_ASYNC,
73 STAT_ASYNC_OK,
74 STAT_ASYNC_NOK,
75 STAT_BADKEYS, /* tx only */
76 STAT_BADMSGS = STAT_BADKEYS, /* rx only */
77 STAT_NOKEYS,
78 STAT_SWITCHES,
79
80 MAX_STATS,
81 };
82
83 /* TIPC crypto statistics' header */
84 static const char *hstats[MAX_STATS] = {"ok", "nok", "async", "async_ok",
85 "async_nok", "badmsgs", "nokeys",
86 "switches"};
87
88 /* Max TFMs number per key */
89 int sysctl_tipc_max_tfms __read_mostly = TIPC_MAX_TFMS_DEF;
90 /* Key exchange switch, default: on */
91 int sysctl_tipc_key_exchange_enabled __read_mostly = 1;
92
93 /*
94 * struct tipc_key - TIPC keys' status indicator
95 *
96 * 7 6 5 4 3 2 1 0
97 * +-----+-----+-----+-----+-----+-----+-----+-----+
98 * key: | (reserved)|passive idx| active idx|pending idx|
99 * +-----+-----+-----+-----+-----+-----+-----+-----+
100 */
101 struct tipc_key {
102 #define KEY_BITS (2)
103 #define KEY_MASK ((1 << KEY_BITS) - 1)
104 union {
105 struct {
106 #if defined(__LITTLE_ENDIAN_BITFIELD)
107 u8 pending:2,
108 active:2,
109 passive:2, /* rx only */
110 reserved:2;
111 #elif defined(__BIG_ENDIAN_BITFIELD)
112 u8 reserved:2,
113 passive:2, /* rx only */
114 active:2,
115 pending:2;
116 #else
117 #error "Please fix <asm/byteorder.h>"
118 #endif
119 } __packed;
120 u8 keys;
121 };
122 };
123
124 /**
125 * struct tipc_tfm - TIPC TFM structure to form a list of TFMs
126 * @tfm: cipher handle/key
127 * @list: linked list of TFMs
128 */
129 struct tipc_tfm {
130 struct crypto_aead *tfm;
131 struct list_head list;
132 };
133
134 /**
135 * struct tipc_aead - TIPC AEAD key structure
136 * @tfm_entry: per-cpu pointer to one entry in TFM list
137 * @crypto: TIPC crypto owns this key
138 * @cloned: reference to the source key in case cloning
139 * @users: the number of the key users (TX/RX)
140 * @salt: the key's SALT value
141 * @authsize: authentication tag size (max = 16)
142 * @mode: crypto mode is applied to the key
143 * @hint: a hint for user key
144 * @rcu: struct rcu_head
145 * @key: the aead key
146 * @gen: the key's generation
147 * @seqno: the key seqno (cluster scope)
148 * @refcnt: the key reference counter
149 */
150 struct tipc_aead {
151 #define TIPC_AEAD_HINT_LEN (5)
152 struct tipc_tfm * __percpu *tfm_entry;
153 struct tipc_crypto *crypto;
154 struct tipc_aead *cloned;
155 atomic_t users;
156 u32 salt;
157 u8 authsize;
158 u8 mode;
159 char hint[2 * TIPC_AEAD_HINT_LEN + 1];
160 struct rcu_head rcu;
161 struct tipc_aead_key *key;
162 u16 gen;
163
164 atomic64_t seqno ____cacheline_aligned;
165 refcount_t refcnt ____cacheline_aligned;
166
167 } ____cacheline_aligned;
168
169 /**
170 * struct tipc_crypto_stats - TIPC Crypto statistics
171 * @stat: array of crypto statistics
172 */
173 struct tipc_crypto_stats {
174 unsigned int stat[MAX_STATS];
175 };
176
177 /**
178 * struct tipc_crypto - TIPC TX/RX crypto structure
179 * @net: struct net
180 * @node: TIPC node (RX)
181 * @aead: array of pointers to AEAD keys for encryption/decryption
182 * @peer_rx_active: replicated peer RX active key index
183 * @key_gen: TX/RX key generation
184 * @key: the key states
185 * @skey_mode: session key's mode
186 * @skey: received session key
187 * @wq: common workqueue on TX crypto
188 * @work: delayed work sched for TX/RX
189 * @key_distr: key distributing state
190 * @rekeying_intv: rekeying interval (in minutes)
191 * @stats: the crypto statistics
192 * @name: the crypto name
193 * @sndnxt: the per-peer sndnxt (TX)
194 * @timer1: general timer 1 (jiffies)
195 * @timer2: general timer 2 (jiffies)
196 * @working: the crypto is working or not
197 * @key_master: flag indicates if master key exists
198 * @legacy_user: flag indicates if a peer joins w/o master key (for bwd comp.)
199 * @nokey: no key indication
200 * @flags: combined flags field
201 * @lock: tipc_key lock
202 */
203 struct tipc_crypto {
204 struct net *net;
205 struct tipc_node *node;
206 struct tipc_aead __rcu *aead[KEY_MAX + 1];
207 atomic_t peer_rx_active;
208 u16 key_gen;
209 struct tipc_key key;
210 u8 skey_mode;
211 struct tipc_aead_key *skey;
212 struct workqueue_struct *wq;
213 struct delayed_work work;
214 #define KEY_DISTR_SCHED 1
215 #define KEY_DISTR_COMPL 2
216 atomic_t key_distr;
217 u32 rekeying_intv;
218
219 struct tipc_crypto_stats __percpu *stats;
220 char name[48];
221
222 atomic64_t sndnxt ____cacheline_aligned;
223 unsigned long timer1;
224 unsigned long timer2;
225 union {
226 struct {
227 u8 working:1;
228 u8 key_master:1;
229 u8 legacy_user:1;
230 u8 nokey: 1;
231 };
232 u8 flags;
233 };
234 spinlock_t lock; /* crypto lock */
235
236 } ____cacheline_aligned;
237
238 /* struct tipc_crypto_tx_ctx - TX context for callbacks */
239 struct tipc_crypto_tx_ctx {
240 struct tipc_aead *aead;
241 struct tipc_bearer *bearer;
242 struct tipc_media_addr dst;
243 };
244
245 /* struct tipc_crypto_rx_ctx - RX context for callbacks */
246 struct tipc_crypto_rx_ctx {
247 struct tipc_aead *aead;
248 struct tipc_bearer *bearer;
249 };
250
251 static struct tipc_aead *tipc_aead_get(struct tipc_aead __rcu *aead);
252 static inline void tipc_aead_put(struct tipc_aead *aead);
253 static void tipc_aead_free(struct rcu_head *rp);
254 static int tipc_aead_users(struct tipc_aead __rcu *aead);
255 static void tipc_aead_users_inc(struct tipc_aead __rcu *aead, int lim);
256 static void tipc_aead_users_dec(struct tipc_aead __rcu *aead, int lim);
257 static void tipc_aead_users_set(struct tipc_aead __rcu *aead, int val);
258 static struct crypto_aead *tipc_aead_tfm_next(struct tipc_aead *aead);
259 static int tipc_aead_init(struct tipc_aead **aead, struct tipc_aead_key *ukey,
260 u8 mode);
261 static int tipc_aead_clone(struct tipc_aead **dst, struct tipc_aead *src);
262 static void *tipc_aead_mem_alloc(struct crypto_aead *tfm,
263 unsigned int crypto_ctx_size,
264 u8 **iv, struct aead_request **req,
265 struct scatterlist **sg, int nsg);
266 static int tipc_aead_encrypt(struct tipc_aead *aead, struct sk_buff *skb,
267 struct tipc_bearer *b,
268 struct tipc_media_addr *dst,
269 struct tipc_node *__dnode);
270 static void tipc_aead_encrypt_done(void *data, int err);
271 static int tipc_aead_decrypt(struct net *net, struct tipc_aead *aead,
272 struct sk_buff *skb, struct tipc_bearer *b);
273 static void tipc_aead_decrypt_done(void *data, int err);
274 static inline int tipc_ehdr_size(struct tipc_ehdr *ehdr);
275 static int tipc_ehdr_build(struct net *net, struct tipc_aead *aead,
276 u8 tx_key, struct sk_buff *skb,
277 struct tipc_crypto *__rx);
278 static inline void tipc_crypto_key_set_state(struct tipc_crypto *c,
279 u8 new_passive,
280 u8 new_active,
281 u8 new_pending);
282 static int tipc_crypto_key_attach(struct tipc_crypto *c,
283 struct tipc_aead *aead, u8 pos,
284 bool master_key);
285 static bool tipc_crypto_key_try_align(struct tipc_crypto *rx, u8 new_pending);
286 static struct tipc_aead *tipc_crypto_key_pick_tx(struct tipc_crypto *tx,
287 struct tipc_crypto *rx,
288 struct sk_buff *skb,
289 u8 tx_key);
290 static void tipc_crypto_key_synch(struct tipc_crypto *rx, struct sk_buff *skb);
291 static int tipc_crypto_key_revoke(struct net *net, u8 tx_key);
292 static inline void tipc_crypto_clone_msg(struct net *net, struct sk_buff *_skb,
293 struct tipc_bearer *b,
294 struct tipc_media_addr *dst,
295 struct tipc_node *__dnode, u8 type);
296 static void tipc_crypto_rcv_complete(struct net *net, struct tipc_aead *aead,
297 struct tipc_bearer *b,
298 struct sk_buff **skb, int err);
299 static void tipc_crypto_do_cmd(struct net *net, int cmd);
300 static char *tipc_crypto_key_dump(struct tipc_crypto *c, char *buf);
301 static char *tipc_key_change_dump(struct tipc_key old, struct tipc_key new,
302 char *buf);
303 static int tipc_crypto_key_xmit(struct net *net, struct tipc_aead_key *skey,
304 u16 gen, u8 mode, u32 dnode);
305 static bool tipc_crypto_key_rcv(struct tipc_crypto *rx, struct tipc_msg *hdr);
306 static void tipc_crypto_work_tx(struct work_struct *work);
307 static void tipc_crypto_work_rx(struct work_struct *work);
308 static int tipc_aead_key_generate(struct tipc_aead_key *skey);
309
310 #define is_tx(crypto) (!(crypto)->node)
311 #define is_rx(crypto) (!is_tx(crypto))
312
313 #define key_next(cur) ((cur) % KEY_MAX + 1)
314
315 #define tipc_aead_rcu_ptr(rcu_ptr, lock) \
316 rcu_dereference_protected((rcu_ptr), lockdep_is_held(lock))
317
318 #define tipc_aead_rcu_replace(rcu_ptr, ptr, lock) \
319 do { \
320 struct tipc_aead *__tmp = rcu_dereference_protected((rcu_ptr), \
321 lockdep_is_held(lock)); \
322 rcu_assign_pointer((rcu_ptr), (ptr)); \
323 tipc_aead_put(__tmp); \
324 } while (0)
325
326 #define tipc_crypto_key_detach(rcu_ptr, lock) \
327 tipc_aead_rcu_replace((rcu_ptr), NULL, lock)
328
329 /**
330 * tipc_aead_key_validate - Validate a AEAD user key
331 * @ukey: pointer to user key data
332 * @info: netlink info pointer
333 */
tipc_aead_key_validate(struct tipc_aead_key * ukey,struct genl_info * info)334 int tipc_aead_key_validate(struct tipc_aead_key *ukey, struct genl_info *info)
335 {
336 int keylen;
337
338 /* Check if algorithm exists */
339 if (unlikely(!crypto_has_alg(ukey->alg_name, 0, 0))) {
340 GENL_SET_ERR_MSG(info, "unable to load the algorithm (module existed?)");
341 return -ENODEV;
342 }
343
344 /* Currently, we only support the "gcm(aes)" cipher algorithm */
345 if (strcmp(ukey->alg_name, "gcm(aes)")) {
346 GENL_SET_ERR_MSG(info, "not supported yet the algorithm");
347 return -ENOTSUPP;
348 }
349
350 /* Check if key size is correct */
351 keylen = ukey->keylen - TIPC_AES_GCM_SALT_SIZE;
352 if (unlikely(keylen != TIPC_AES_GCM_KEY_SIZE_128 &&
353 keylen != TIPC_AES_GCM_KEY_SIZE_192 &&
354 keylen != TIPC_AES_GCM_KEY_SIZE_256)) {
355 GENL_SET_ERR_MSG(info, "incorrect key length (20, 28 or 36 octets?)");
356 return -EKEYREJECTED;
357 }
358
359 return 0;
360 }
361
362 /**
363 * tipc_aead_key_generate - Generate new session key
364 * @skey: input/output key with new content
365 *
366 * Return: 0 in case of success, otherwise < 0
367 */
tipc_aead_key_generate(struct tipc_aead_key * skey)368 static int tipc_aead_key_generate(struct tipc_aead_key *skey)
369 {
370 int rc = 0;
371
372 /* Fill the key's content with a random value via RNG cipher */
373 rc = crypto_get_default_rng();
374 if (likely(!rc)) {
375 rc = crypto_rng_get_bytes(crypto_default_rng, skey->key,
376 skey->keylen);
377 crypto_put_default_rng();
378 }
379
380 return rc;
381 }
382
tipc_aead_get(struct tipc_aead __rcu * aead)383 static struct tipc_aead *tipc_aead_get(struct tipc_aead __rcu *aead)
384 {
385 struct tipc_aead *tmp;
386
387 rcu_read_lock();
388 tmp = rcu_dereference(aead);
389 if (unlikely(!tmp || !refcount_inc_not_zero(&tmp->refcnt)))
390 tmp = NULL;
391 rcu_read_unlock();
392
393 return tmp;
394 }
395
tipc_aead_put(struct tipc_aead * aead)396 static inline void tipc_aead_put(struct tipc_aead *aead)
397 {
398 if (aead && refcount_dec_and_test(&aead->refcnt))
399 call_rcu(&aead->rcu, tipc_aead_free);
400 }
401
402 /**
403 * tipc_aead_free - Release AEAD key incl. all the TFMs in the list
404 * @rp: rcu head pointer
405 */
tipc_aead_free(struct rcu_head * rp)406 static void tipc_aead_free(struct rcu_head *rp)
407 {
408 struct tipc_aead *aead = container_of(rp, struct tipc_aead, rcu);
409 struct tipc_tfm *tfm_entry, *head, *tmp;
410
411 if (aead->cloned) {
412 tipc_aead_put(aead->cloned);
413 } else {
414 head = *get_cpu_ptr(aead->tfm_entry);
415 put_cpu_ptr(aead->tfm_entry);
416 list_for_each_entry_safe(tfm_entry, tmp, &head->list, list) {
417 crypto_free_aead(tfm_entry->tfm);
418 list_del(&tfm_entry->list);
419 kfree(tfm_entry);
420 }
421 /* Free the head */
422 crypto_free_aead(head->tfm);
423 list_del(&head->list);
424 kfree(head);
425 }
426 free_percpu(aead->tfm_entry);
427 kfree_sensitive(aead->key);
428 kfree(aead);
429 }
430
tipc_aead_users(struct tipc_aead __rcu * aead)431 static int tipc_aead_users(struct tipc_aead __rcu *aead)
432 {
433 struct tipc_aead *tmp;
434 int users = 0;
435
436 rcu_read_lock();
437 tmp = rcu_dereference(aead);
438 if (tmp)
439 users = atomic_read(&tmp->users);
440 rcu_read_unlock();
441
442 return users;
443 }
444
tipc_aead_users_inc(struct tipc_aead __rcu * aead,int lim)445 static void tipc_aead_users_inc(struct tipc_aead __rcu *aead, int lim)
446 {
447 struct tipc_aead *tmp;
448
449 rcu_read_lock();
450 tmp = rcu_dereference(aead);
451 if (tmp)
452 atomic_add_unless(&tmp->users, 1, lim);
453 rcu_read_unlock();
454 }
455
tipc_aead_users_dec(struct tipc_aead __rcu * aead,int lim)456 static void tipc_aead_users_dec(struct tipc_aead __rcu *aead, int lim)
457 {
458 struct tipc_aead *tmp;
459
460 rcu_read_lock();
461 tmp = rcu_dereference(aead);
462 if (tmp)
463 atomic_add_unless(&rcu_dereference(aead)->users, -1, lim);
464 rcu_read_unlock();
465 }
466
tipc_aead_users_set(struct tipc_aead __rcu * aead,int val)467 static void tipc_aead_users_set(struct tipc_aead __rcu *aead, int val)
468 {
469 struct tipc_aead *tmp;
470 int cur;
471
472 rcu_read_lock();
473 tmp = rcu_dereference(aead);
474 if (tmp) {
475 do {
476 cur = atomic_read(&tmp->users);
477 if (cur == val)
478 break;
479 } while (atomic_cmpxchg(&tmp->users, cur, val) != cur);
480 }
481 rcu_read_unlock();
482 }
483
484 /**
485 * tipc_aead_tfm_next - Move TFM entry to the next one in list and return it
486 * @aead: the AEAD key pointer
487 */
tipc_aead_tfm_next(struct tipc_aead * aead)488 static struct crypto_aead *tipc_aead_tfm_next(struct tipc_aead *aead)
489 {
490 struct tipc_tfm **tfm_entry;
491 struct crypto_aead *tfm;
492
493 tfm_entry = get_cpu_ptr(aead->tfm_entry);
494 *tfm_entry = list_next_entry(*tfm_entry, list);
495 tfm = (*tfm_entry)->tfm;
496 put_cpu_ptr(tfm_entry);
497
498 return tfm;
499 }
500
501 /**
502 * tipc_aead_init - Initiate TIPC AEAD
503 * @aead: returned new TIPC AEAD key handle pointer
504 * @ukey: pointer to user key data
505 * @mode: the key mode
506 *
507 * Allocate a (list of) new cipher transformation (TFM) with the specific user
508 * key data if valid. The number of the allocated TFMs can be set via the sysfs
509 * "net/tipc/max_tfms" first.
510 * Also, all the other AEAD data are also initialized.
511 *
512 * Return: 0 if the initiation is successful, otherwise: < 0
513 */
tipc_aead_init(struct tipc_aead ** aead,struct tipc_aead_key * ukey,u8 mode)514 static int tipc_aead_init(struct tipc_aead **aead, struct tipc_aead_key *ukey,
515 u8 mode)
516 {
517 struct tipc_tfm *tfm_entry, *head;
518 struct crypto_aead *tfm;
519 struct tipc_aead *tmp;
520 int keylen, err, cpu;
521 int tfm_cnt = 0;
522
523 if (unlikely(*aead))
524 return -EEXIST;
525
526 /* Allocate a new AEAD */
527 tmp = kzalloc(sizeof(*tmp), GFP_ATOMIC);
528 if (unlikely(!tmp))
529 return -ENOMEM;
530
531 /* The key consists of two parts: [AES-KEY][SALT] */
532 keylen = ukey->keylen - TIPC_AES_GCM_SALT_SIZE;
533
534 /* Allocate per-cpu TFM entry pointer */
535 tmp->tfm_entry = alloc_percpu(struct tipc_tfm *);
536 if (!tmp->tfm_entry) {
537 kfree_sensitive(tmp);
538 return -ENOMEM;
539 }
540
541 /* Make a list of TFMs with the user key data */
542 do {
543 tfm = crypto_alloc_aead(ukey->alg_name, 0, 0);
544 if (IS_ERR(tfm)) {
545 err = PTR_ERR(tfm);
546 break;
547 }
548
549 if (unlikely(!tfm_cnt &&
550 crypto_aead_ivsize(tfm) != TIPC_AES_GCM_IV_SIZE)) {
551 crypto_free_aead(tfm);
552 err = -ENOTSUPP;
553 break;
554 }
555
556 err = crypto_aead_setauthsize(tfm, TIPC_AES_GCM_TAG_SIZE);
557 err |= crypto_aead_setkey(tfm, ukey->key, keylen);
558 if (unlikely(err)) {
559 crypto_free_aead(tfm);
560 break;
561 }
562
563 tfm_entry = kmalloc(sizeof(*tfm_entry), GFP_KERNEL);
564 if (unlikely(!tfm_entry)) {
565 crypto_free_aead(tfm);
566 err = -ENOMEM;
567 break;
568 }
569 INIT_LIST_HEAD(&tfm_entry->list);
570 tfm_entry->tfm = tfm;
571
572 /* First entry? */
573 if (!tfm_cnt) {
574 head = tfm_entry;
575 for_each_possible_cpu(cpu) {
576 *per_cpu_ptr(tmp->tfm_entry, cpu) = head;
577 }
578 } else {
579 list_add_tail(&tfm_entry->list, &head->list);
580 }
581
582 } while (++tfm_cnt < sysctl_tipc_max_tfms);
583
584 /* Not any TFM is allocated? */
585 if (!tfm_cnt) {
586 free_percpu(tmp->tfm_entry);
587 kfree_sensitive(tmp);
588 return err;
589 }
590
591 /* Form a hex string of some last bytes as the key's hint */
592 bin2hex(tmp->hint, ukey->key + keylen - TIPC_AEAD_HINT_LEN,
593 TIPC_AEAD_HINT_LEN);
594
595 /* Initialize the other data */
596 tmp->mode = mode;
597 tmp->cloned = NULL;
598 tmp->authsize = TIPC_AES_GCM_TAG_SIZE;
599 tmp->key = kmemdup(ukey, tipc_aead_key_size(ukey), GFP_KERNEL);
600 if (!tmp->key) {
601 tipc_aead_free(&tmp->rcu);
602 return -ENOMEM;
603 }
604 memcpy(&tmp->salt, ukey->key + keylen, TIPC_AES_GCM_SALT_SIZE);
605 atomic_set(&tmp->users, 0);
606 atomic64_set(&tmp->seqno, 0);
607 refcount_set(&tmp->refcnt, 1);
608
609 *aead = tmp;
610 return 0;
611 }
612
613 /**
614 * tipc_aead_clone - Clone a TIPC AEAD key
615 * @dst: dest key for the cloning
616 * @src: source key to clone from
617 *
618 * Make a "copy" of the source AEAD key data to the dest, the TFMs list is
619 * common for the keys.
620 * A reference to the source is hold in the "cloned" pointer for the later
621 * freeing purposes.
622 *
623 * Note: this must be done in cluster-key mode only!
624 * Return: 0 in case of success, otherwise < 0
625 */
tipc_aead_clone(struct tipc_aead ** dst,struct tipc_aead * src)626 static int tipc_aead_clone(struct tipc_aead **dst, struct tipc_aead *src)
627 {
628 struct tipc_aead *aead;
629 int cpu;
630
631 if (!src)
632 return -ENOKEY;
633
634 if (src->mode != CLUSTER_KEY)
635 return -EINVAL;
636
637 if (unlikely(*dst))
638 return -EEXIST;
639
640 aead = kzalloc(sizeof(*aead), GFP_ATOMIC);
641 if (unlikely(!aead))
642 return -ENOMEM;
643
644 aead->tfm_entry = alloc_percpu_gfp(struct tipc_tfm *, GFP_ATOMIC);
645 if (unlikely(!aead->tfm_entry)) {
646 kfree_sensitive(aead);
647 return -ENOMEM;
648 }
649
650 for_each_possible_cpu(cpu) {
651 *per_cpu_ptr(aead->tfm_entry, cpu) =
652 *per_cpu_ptr(src->tfm_entry, cpu);
653 }
654
655 memcpy(aead->hint, src->hint, sizeof(src->hint));
656 aead->mode = src->mode;
657 aead->salt = src->salt;
658 aead->authsize = src->authsize;
659 atomic_set(&aead->users, 0);
660 atomic64_set(&aead->seqno, 0);
661 refcount_set(&aead->refcnt, 1);
662
663 WARN_ON(!refcount_inc_not_zero(&src->refcnt));
664 aead->cloned = src;
665
666 *dst = aead;
667 return 0;
668 }
669
670 /**
671 * tipc_aead_mem_alloc - Allocate memory for AEAD request operations
672 * @tfm: cipher handle to be registered with the request
673 * @crypto_ctx_size: size of crypto context for callback
674 * @iv: returned pointer to IV data
675 * @req: returned pointer to AEAD request data
676 * @sg: returned pointer to SG lists
677 * @nsg: number of SG lists to be allocated
678 *
679 * Allocate memory to store the crypto context data, AEAD request, IV and SG
680 * lists, the memory layout is as follows:
681 * crypto_ctx || iv || aead_req || sg[]
682 *
683 * Return: the pointer to the memory areas in case of success, otherwise NULL
684 */
tipc_aead_mem_alloc(struct crypto_aead * tfm,unsigned int crypto_ctx_size,u8 ** iv,struct aead_request ** req,struct scatterlist ** sg,int nsg)685 static void *tipc_aead_mem_alloc(struct crypto_aead *tfm,
686 unsigned int crypto_ctx_size,
687 u8 **iv, struct aead_request **req,
688 struct scatterlist **sg, int nsg)
689 {
690 unsigned int iv_size, req_size;
691 unsigned int len;
692 u8 *mem;
693
694 iv_size = crypto_aead_ivsize(tfm);
695 req_size = sizeof(**req) + crypto_aead_reqsize(tfm);
696
697 len = crypto_ctx_size;
698 len += iv_size;
699 len += crypto_aead_alignmask(tfm) & ~(crypto_tfm_ctx_alignment() - 1);
700 len = ALIGN(len, crypto_tfm_ctx_alignment());
701 len += req_size;
702 len = ALIGN(len, __alignof__(struct scatterlist));
703 len += nsg * sizeof(**sg);
704
705 mem = kmalloc(len, GFP_ATOMIC);
706 if (!mem)
707 return NULL;
708
709 *iv = (u8 *)PTR_ALIGN(mem + crypto_ctx_size,
710 crypto_aead_alignmask(tfm) + 1);
711 *req = (struct aead_request *)PTR_ALIGN(*iv + iv_size,
712 crypto_tfm_ctx_alignment());
713 *sg = (struct scatterlist *)PTR_ALIGN((u8 *)*req + req_size,
714 __alignof__(struct scatterlist));
715
716 return (void *)mem;
717 }
718
719 /**
720 * tipc_aead_encrypt - Encrypt a message
721 * @aead: TIPC AEAD key for the message encryption
722 * @skb: the input/output skb
723 * @b: TIPC bearer where the message will be delivered after the encryption
724 * @dst: the destination media address
725 * @__dnode: TIPC dest node if "known"
726 *
727 * Return:
728 * * 0 : if the encryption has completed
729 * * -EINPROGRESS/-EBUSY : if a callback will be performed
730 * * < 0 : the encryption has failed
731 */
tipc_aead_encrypt(struct tipc_aead * aead,struct sk_buff * skb,struct tipc_bearer * b,struct tipc_media_addr * dst,struct tipc_node * __dnode)732 static int tipc_aead_encrypt(struct tipc_aead *aead, struct sk_buff *skb,
733 struct tipc_bearer *b,
734 struct tipc_media_addr *dst,
735 struct tipc_node *__dnode)
736 {
737 struct crypto_aead *tfm = tipc_aead_tfm_next(aead);
738 struct tipc_crypto_tx_ctx *tx_ctx;
739 struct aead_request *req;
740 struct sk_buff *trailer;
741 struct scatterlist *sg;
742 struct tipc_ehdr *ehdr;
743 int ehsz, len, tailen, nsg, rc;
744 void *ctx;
745 u32 salt;
746 u8 *iv;
747
748 /* Make sure message len at least 4-byte aligned */
749 len = ALIGN(skb->len, 4);
750 tailen = len - skb->len + aead->authsize;
751
752 /* Expand skb tail for authentication tag:
753 * As for simplicity, we'd have made sure skb having enough tailroom
754 * for authentication tag @skb allocation. Even when skb is nonlinear
755 * but there is no frag_list, it should be still fine!
756 * Otherwise, we must cow it to be a writable buffer with the tailroom.
757 */
758 SKB_LINEAR_ASSERT(skb);
759 if (tailen > skb_tailroom(skb)) {
760 pr_debug("TX(): skb tailroom is not enough: %d, requires: %d\n",
761 skb_tailroom(skb), tailen);
762 }
763
764 nsg = skb_cow_data(skb, tailen, &trailer);
765 if (unlikely(nsg < 0)) {
766 pr_err("TX: skb_cow_data() returned %d\n", nsg);
767 return nsg;
768 }
769
770 pskb_put(skb, trailer, tailen);
771
772 /* Allocate memory for the AEAD operation */
773 ctx = tipc_aead_mem_alloc(tfm, sizeof(*tx_ctx), &iv, &req, &sg, nsg);
774 if (unlikely(!ctx))
775 return -ENOMEM;
776 TIPC_SKB_CB(skb)->crypto_ctx = ctx;
777
778 /* Map skb to the sg lists */
779 sg_init_table(sg, nsg);
780 rc = skb_to_sgvec(skb, sg, 0, skb->len);
781 if (unlikely(rc < 0)) {
782 pr_err("TX: skb_to_sgvec() returned %d, nsg %d!\n", rc, nsg);
783 goto exit;
784 }
785
786 /* Prepare IV: [SALT (4 octets)][SEQNO (8 octets)]
787 * In case we're in cluster-key mode, SALT is varied by xor-ing with
788 * the source address (or w0 of id), otherwise with the dest address
789 * if dest is known.
790 */
791 ehdr = (struct tipc_ehdr *)skb->data;
792 salt = aead->salt;
793 if (aead->mode == CLUSTER_KEY)
794 salt ^= __be32_to_cpu(ehdr->addr);
795 else if (__dnode)
796 salt ^= tipc_node_get_addr(__dnode);
797 memcpy(iv, &salt, 4);
798 memcpy(iv + 4, (u8 *)&ehdr->seqno, 8);
799
800 /* Prepare request */
801 ehsz = tipc_ehdr_size(ehdr);
802 aead_request_set_tfm(req, tfm);
803 aead_request_set_ad(req, ehsz);
804 aead_request_set_crypt(req, sg, sg, len - ehsz, iv);
805
806 /* Set callback function & data */
807 aead_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
808 tipc_aead_encrypt_done, skb);
809 tx_ctx = (struct tipc_crypto_tx_ctx *)ctx;
810 tx_ctx->aead = aead;
811 tx_ctx->bearer = b;
812 memcpy(&tx_ctx->dst, dst, sizeof(*dst));
813
814 /* Hold bearer */
815 if (unlikely(!tipc_bearer_hold(b))) {
816 rc = -ENODEV;
817 goto exit;
818 }
819
820 /* Get net to avoid freed tipc_crypto when delete namespace */
821 get_net(aead->crypto->net);
822
823 /* Now, do encrypt */
824 rc = crypto_aead_encrypt(req);
825 if (rc == -EINPROGRESS || rc == -EBUSY)
826 return rc;
827
828 tipc_bearer_put(b);
829 put_net(aead->crypto->net);
830
831 exit:
832 kfree(ctx);
833 TIPC_SKB_CB(skb)->crypto_ctx = NULL;
834 return rc;
835 }
836
tipc_aead_encrypt_done(void * data,int err)837 static void tipc_aead_encrypt_done(void *data, int err)
838 {
839 struct sk_buff *skb = data;
840 struct tipc_crypto_tx_ctx *tx_ctx = TIPC_SKB_CB(skb)->crypto_ctx;
841 struct tipc_bearer *b = tx_ctx->bearer;
842 struct tipc_aead *aead = tx_ctx->aead;
843 struct tipc_crypto *tx = aead->crypto;
844 struct net *net = tx->net;
845
846 switch (err) {
847 case 0:
848 this_cpu_inc(tx->stats->stat[STAT_ASYNC_OK]);
849 rcu_read_lock();
850 if (likely(test_bit(0, &b->up)))
851 b->media->send_msg(net, skb, b, &tx_ctx->dst);
852 else
853 kfree_skb(skb);
854 rcu_read_unlock();
855 break;
856 case -EINPROGRESS:
857 return;
858 default:
859 this_cpu_inc(tx->stats->stat[STAT_ASYNC_NOK]);
860 kfree_skb(skb);
861 break;
862 }
863
864 kfree(tx_ctx);
865 tipc_bearer_put(b);
866 tipc_aead_put(aead);
867 put_net(net);
868 }
869
870 /**
871 * tipc_aead_decrypt - Decrypt an encrypted message
872 * @net: struct net
873 * @aead: TIPC AEAD for the message decryption
874 * @skb: the input/output skb
875 * @b: TIPC bearer where the message has been received
876 *
877 * Return:
878 * * 0 : if the decryption has completed
879 * * -EINPROGRESS/-EBUSY : if a callback will be performed
880 * * < 0 : the decryption has failed
881 */
tipc_aead_decrypt(struct net * net,struct tipc_aead * aead,struct sk_buff * skb,struct tipc_bearer * b)882 static int tipc_aead_decrypt(struct net *net, struct tipc_aead *aead,
883 struct sk_buff *skb, struct tipc_bearer *b)
884 {
885 struct tipc_crypto_rx_ctx *rx_ctx;
886 struct aead_request *req;
887 struct crypto_aead *tfm;
888 struct sk_buff *unused;
889 struct scatterlist *sg;
890 struct tipc_ehdr *ehdr;
891 int ehsz, nsg, rc;
892 void *ctx;
893 u32 salt;
894 u8 *iv;
895
896 if (unlikely(!aead))
897 return -ENOKEY;
898
899 nsg = skb_cow_data(skb, 0, &unused);
900 if (unlikely(nsg < 0)) {
901 pr_err("RX: skb_cow_data() returned %d\n", nsg);
902 return nsg;
903 }
904
905 /* Allocate memory for the AEAD operation */
906 tfm = tipc_aead_tfm_next(aead);
907 ctx = tipc_aead_mem_alloc(tfm, sizeof(*rx_ctx), &iv, &req, &sg, nsg);
908 if (unlikely(!ctx))
909 return -ENOMEM;
910 TIPC_SKB_CB(skb)->crypto_ctx = ctx;
911
912 /* Map skb to the sg lists */
913 sg_init_table(sg, nsg);
914 rc = skb_to_sgvec(skb, sg, 0, skb->len);
915 if (unlikely(rc < 0)) {
916 pr_err("RX: skb_to_sgvec() returned %d, nsg %d\n", rc, nsg);
917 goto exit;
918 }
919
920 /* Reconstruct IV: */
921 ehdr = (struct tipc_ehdr *)skb->data;
922 salt = aead->salt;
923 if (aead->mode == CLUSTER_KEY)
924 salt ^= __be32_to_cpu(ehdr->addr);
925 else if (ehdr->destined)
926 salt ^= tipc_own_addr(net);
927 memcpy(iv, &salt, 4);
928 memcpy(iv + 4, (u8 *)&ehdr->seqno, 8);
929
930 /* Prepare request */
931 ehsz = tipc_ehdr_size(ehdr);
932 aead_request_set_tfm(req, tfm);
933 aead_request_set_ad(req, ehsz);
934 aead_request_set_crypt(req, sg, sg, skb->len - ehsz, iv);
935
936 /* Set callback function & data */
937 aead_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
938 tipc_aead_decrypt_done, skb);
939 rx_ctx = (struct tipc_crypto_rx_ctx *)ctx;
940 rx_ctx->aead = aead;
941 rx_ctx->bearer = b;
942
943 /* Hold bearer */
944 if (unlikely(!tipc_bearer_hold(b))) {
945 rc = -ENODEV;
946 goto exit;
947 }
948
949 /* Now, do decrypt */
950 rc = crypto_aead_decrypt(req);
951 if (rc == -EINPROGRESS || rc == -EBUSY)
952 return rc;
953
954 tipc_bearer_put(b);
955
956 exit:
957 kfree(ctx);
958 TIPC_SKB_CB(skb)->crypto_ctx = NULL;
959 return rc;
960 }
961
tipc_aead_decrypt_done(void * data,int err)962 static void tipc_aead_decrypt_done(void *data, int err)
963 {
964 struct sk_buff *skb = data;
965 struct tipc_crypto_rx_ctx *rx_ctx = TIPC_SKB_CB(skb)->crypto_ctx;
966 struct tipc_bearer *b = rx_ctx->bearer;
967 struct tipc_aead *aead = rx_ctx->aead;
968 struct tipc_crypto_stats __percpu *stats = aead->crypto->stats;
969 struct net *net = aead->crypto->net;
970
971 switch (err) {
972 case 0:
973 this_cpu_inc(stats->stat[STAT_ASYNC_OK]);
974 break;
975 case -EINPROGRESS:
976 return;
977 default:
978 this_cpu_inc(stats->stat[STAT_ASYNC_NOK]);
979 break;
980 }
981
982 kfree(rx_ctx);
983 tipc_crypto_rcv_complete(net, aead, b, &skb, err);
984 if (likely(skb)) {
985 if (likely(test_bit(0, &b->up)))
986 tipc_rcv(net, skb, b);
987 else
988 kfree_skb(skb);
989 }
990
991 tipc_bearer_put(b);
992 }
993
tipc_ehdr_size(struct tipc_ehdr * ehdr)994 static inline int tipc_ehdr_size(struct tipc_ehdr *ehdr)
995 {
996 return (ehdr->user != LINK_CONFIG) ? EHDR_SIZE : EHDR_CFG_SIZE;
997 }
998
999 /**
1000 * tipc_ehdr_validate - Validate an encryption message
1001 * @skb: the message buffer
1002 *
1003 * Return: "true" if this is a valid encryption message, otherwise "false"
1004 */
tipc_ehdr_validate(struct sk_buff * skb)1005 bool tipc_ehdr_validate(struct sk_buff *skb)
1006 {
1007 struct tipc_ehdr *ehdr;
1008 int ehsz;
1009
1010 if (unlikely(!pskb_may_pull(skb, EHDR_MIN_SIZE)))
1011 return false;
1012
1013 ehdr = (struct tipc_ehdr *)skb->data;
1014 if (unlikely(ehdr->version != TIPC_EVERSION))
1015 return false;
1016 ehsz = tipc_ehdr_size(ehdr);
1017 if (unlikely(!pskb_may_pull(skb, ehsz)))
1018 return false;
1019 if (unlikely(skb->len <= ehsz + TIPC_AES_GCM_TAG_SIZE))
1020 return false;
1021
1022 return true;
1023 }
1024
1025 /**
1026 * tipc_ehdr_build - Build TIPC encryption message header
1027 * @net: struct net
1028 * @aead: TX AEAD key to be used for the message encryption
1029 * @tx_key: key id used for the message encryption
1030 * @skb: input/output message skb
1031 * @__rx: RX crypto handle if dest is "known"
1032 *
1033 * Return: the header size if the building is successful, otherwise < 0
1034 */
tipc_ehdr_build(struct net * net,struct tipc_aead * aead,u8 tx_key,struct sk_buff * skb,struct tipc_crypto * __rx)1035 static int tipc_ehdr_build(struct net *net, struct tipc_aead *aead,
1036 u8 tx_key, struct sk_buff *skb,
1037 struct tipc_crypto *__rx)
1038 {
1039 struct tipc_msg *hdr = buf_msg(skb);
1040 struct tipc_ehdr *ehdr;
1041 u32 user = msg_user(hdr);
1042 u64 seqno;
1043 int ehsz;
1044
1045 /* Make room for encryption header */
1046 ehsz = (user != LINK_CONFIG) ? EHDR_SIZE : EHDR_CFG_SIZE;
1047 WARN_ON(skb_headroom(skb) < ehsz);
1048 ehdr = (struct tipc_ehdr *)skb_push(skb, ehsz);
1049
1050 /* Obtain a seqno first:
1051 * Use the key seqno (= cluster wise) if dest is unknown or we're in
1052 * cluster key mode, otherwise it's better for a per-peer seqno!
1053 */
1054 if (!__rx || aead->mode == CLUSTER_KEY)
1055 seqno = atomic64_inc_return(&aead->seqno);
1056 else
1057 seqno = atomic64_inc_return(&__rx->sndnxt);
1058
1059 /* Revoke the key if seqno is wrapped around */
1060 if (unlikely(!seqno))
1061 return tipc_crypto_key_revoke(net, tx_key);
1062
1063 /* Word 1-2 */
1064 ehdr->seqno = cpu_to_be64(seqno);
1065
1066 /* Words 0, 3- */
1067 ehdr->version = TIPC_EVERSION;
1068 ehdr->user = 0;
1069 ehdr->keepalive = 0;
1070 ehdr->tx_key = tx_key;
1071 ehdr->destined = (__rx) ? 1 : 0;
1072 ehdr->rx_key_active = (__rx) ? __rx->key.active : 0;
1073 ehdr->rx_nokey = (__rx) ? __rx->nokey : 0;
1074 ehdr->master_key = aead->crypto->key_master;
1075 ehdr->reserved_1 = 0;
1076 ehdr->reserved_2 = 0;
1077
1078 switch (user) {
1079 case LINK_CONFIG:
1080 ehdr->user = LINK_CONFIG;
1081 memcpy(ehdr->id, tipc_own_id(net), NODE_ID_LEN);
1082 break;
1083 default:
1084 if (user == LINK_PROTOCOL && msg_type(hdr) == STATE_MSG) {
1085 ehdr->user = LINK_PROTOCOL;
1086 ehdr->keepalive = msg_is_keepalive(hdr);
1087 }
1088 ehdr->addr = hdr->hdr[3];
1089 break;
1090 }
1091
1092 return ehsz;
1093 }
1094
tipc_crypto_key_set_state(struct tipc_crypto * c,u8 new_passive,u8 new_active,u8 new_pending)1095 static inline void tipc_crypto_key_set_state(struct tipc_crypto *c,
1096 u8 new_passive,
1097 u8 new_active,
1098 u8 new_pending)
1099 {
1100 struct tipc_key old = c->key;
1101 char buf[32];
1102
1103 c->key.keys = ((new_passive & KEY_MASK) << (KEY_BITS * 2)) |
1104 ((new_active & KEY_MASK) << (KEY_BITS)) |
1105 ((new_pending & KEY_MASK));
1106
1107 pr_debug("%s: key changing %s ::%pS\n", c->name,
1108 tipc_key_change_dump(old, c->key, buf),
1109 __builtin_return_address(0));
1110 }
1111
1112 /**
1113 * tipc_crypto_key_init - Initiate a new user / AEAD key
1114 * @c: TIPC crypto to which new key is attached
1115 * @ukey: the user key
1116 * @mode: the key mode (CLUSTER_KEY or PER_NODE_KEY)
1117 * @master_key: specify this is a cluster master key
1118 *
1119 * A new TIPC AEAD key will be allocated and initiated with the specified user
1120 * key, then attached to the TIPC crypto.
1121 *
1122 * Return: new key id in case of success, otherwise: < 0
1123 */
tipc_crypto_key_init(struct tipc_crypto * c,struct tipc_aead_key * ukey,u8 mode,bool master_key)1124 int tipc_crypto_key_init(struct tipc_crypto *c, struct tipc_aead_key *ukey,
1125 u8 mode, bool master_key)
1126 {
1127 struct tipc_aead *aead = NULL;
1128 int rc = 0;
1129
1130 /* Initiate with the new user key */
1131 rc = tipc_aead_init(&aead, ukey, mode);
1132
1133 /* Attach it to the crypto */
1134 if (likely(!rc)) {
1135 rc = tipc_crypto_key_attach(c, aead, 0, master_key);
1136 if (rc < 0)
1137 tipc_aead_free(&aead->rcu);
1138 }
1139
1140 return rc;
1141 }
1142
1143 /**
1144 * tipc_crypto_key_attach - Attach a new AEAD key to TIPC crypto
1145 * @c: TIPC crypto to which the new AEAD key is attached
1146 * @aead: the new AEAD key pointer
1147 * @pos: desired slot in the crypto key array, = 0 if any!
1148 * @master_key: specify this is a cluster master key
1149 *
1150 * Return: new key id in case of success, otherwise: -EBUSY
1151 */
tipc_crypto_key_attach(struct tipc_crypto * c,struct tipc_aead * aead,u8 pos,bool master_key)1152 static int tipc_crypto_key_attach(struct tipc_crypto *c,
1153 struct tipc_aead *aead, u8 pos,
1154 bool master_key)
1155 {
1156 struct tipc_key key;
1157 int rc = -EBUSY;
1158 u8 new_key;
1159
1160 spin_lock_bh(&c->lock);
1161 key = c->key;
1162 if (master_key) {
1163 new_key = KEY_MASTER;
1164 goto attach;
1165 }
1166 if (key.active && key.passive)
1167 goto exit;
1168 if (key.pending) {
1169 if (tipc_aead_users(c->aead[key.pending]) > 0)
1170 goto exit;
1171 /* if (pos): ok with replacing, will be aligned when needed */
1172 /* Replace it */
1173 new_key = key.pending;
1174 } else {
1175 if (pos) {
1176 if (key.active && pos != key_next(key.active)) {
1177 key.passive = pos;
1178 new_key = pos;
1179 goto attach;
1180 } else if (!key.active && !key.passive) {
1181 key.pending = pos;
1182 new_key = pos;
1183 goto attach;
1184 }
1185 }
1186 key.pending = key_next(key.active ?: key.passive);
1187 new_key = key.pending;
1188 }
1189
1190 attach:
1191 aead->crypto = c;
1192 aead->gen = (is_tx(c)) ? ++c->key_gen : c->key_gen;
1193 tipc_aead_rcu_replace(c->aead[new_key], aead, &c->lock);
1194 if (likely(c->key.keys != key.keys))
1195 tipc_crypto_key_set_state(c, key.passive, key.active,
1196 key.pending);
1197 c->working = 1;
1198 c->nokey = 0;
1199 c->key_master |= master_key;
1200 rc = new_key;
1201
1202 exit:
1203 spin_unlock_bh(&c->lock);
1204 return rc;
1205 }
1206
tipc_crypto_key_flush(struct tipc_crypto * c)1207 void tipc_crypto_key_flush(struct tipc_crypto *c)
1208 {
1209 struct tipc_crypto *tx, *rx;
1210 int k;
1211
1212 spin_lock_bh(&c->lock);
1213 if (is_rx(c)) {
1214 /* Try to cancel pending work */
1215 rx = c;
1216 tx = tipc_net(rx->net)->crypto_tx;
1217 if (cancel_delayed_work(&rx->work)) {
1218 kfree(rx->skey);
1219 rx->skey = NULL;
1220 atomic_xchg(&rx->key_distr, 0);
1221 tipc_node_put(rx->node);
1222 }
1223 /* RX stopping => decrease TX key users if any */
1224 k = atomic_xchg(&rx->peer_rx_active, 0);
1225 if (k) {
1226 tipc_aead_users_dec(tx->aead[k], 0);
1227 /* Mark the point TX key users changed */
1228 tx->timer1 = jiffies;
1229 }
1230 }
1231
1232 c->flags = 0;
1233 tipc_crypto_key_set_state(c, 0, 0, 0);
1234 for (k = KEY_MIN; k <= KEY_MAX; k++)
1235 tipc_crypto_key_detach(c->aead[k], &c->lock);
1236 atomic64_set(&c->sndnxt, 0);
1237 spin_unlock_bh(&c->lock);
1238 }
1239
1240 /**
1241 * tipc_crypto_key_try_align - Align RX keys if possible
1242 * @rx: RX crypto handle
1243 * @new_pending: new pending slot if aligned (= TX key from peer)
1244 *
1245 * Peer has used an unknown key slot, this only happens when peer has left and
1246 * rejoned, or we are newcomer.
1247 * That means, there must be no active key but a pending key at unaligned slot.
1248 * If so, we try to move the pending key to the new slot.
1249 * Note: A potential passive key can exist, it will be shifted correspondingly!
1250 *
1251 * Return: "true" if key is successfully aligned, otherwise "false"
1252 */
tipc_crypto_key_try_align(struct tipc_crypto * rx,u8 new_pending)1253 static bool tipc_crypto_key_try_align(struct tipc_crypto *rx, u8 new_pending)
1254 {
1255 struct tipc_aead *tmp1, *tmp2 = NULL;
1256 struct tipc_key key;
1257 bool aligned = false;
1258 u8 new_passive = 0;
1259 int x;
1260
1261 spin_lock(&rx->lock);
1262 key = rx->key;
1263 if (key.pending == new_pending) {
1264 aligned = true;
1265 goto exit;
1266 }
1267 if (key.active)
1268 goto exit;
1269 if (!key.pending)
1270 goto exit;
1271 if (tipc_aead_users(rx->aead[key.pending]) > 0)
1272 goto exit;
1273
1274 /* Try to "isolate" this pending key first */
1275 tmp1 = tipc_aead_rcu_ptr(rx->aead[key.pending], &rx->lock);
1276 if (!refcount_dec_if_one(&tmp1->refcnt))
1277 goto exit;
1278 rcu_assign_pointer(rx->aead[key.pending], NULL);
1279
1280 /* Move passive key if any */
1281 if (key.passive) {
1282 tmp2 = rcu_replace_pointer(rx->aead[key.passive], tmp2, lockdep_is_held(&rx->lock));
1283 x = (key.passive - key.pending + new_pending) % KEY_MAX;
1284 new_passive = (x <= 0) ? x + KEY_MAX : x;
1285 }
1286
1287 /* Re-allocate the key(s) */
1288 tipc_crypto_key_set_state(rx, new_passive, 0, new_pending);
1289 rcu_assign_pointer(rx->aead[new_pending], tmp1);
1290 if (new_passive)
1291 rcu_assign_pointer(rx->aead[new_passive], tmp2);
1292 refcount_set(&tmp1->refcnt, 1);
1293 aligned = true;
1294 pr_info_ratelimited("%s: key[%d] -> key[%d]\n", rx->name, key.pending,
1295 new_pending);
1296
1297 exit:
1298 spin_unlock(&rx->lock);
1299 return aligned;
1300 }
1301
1302 /**
1303 * tipc_crypto_key_pick_tx - Pick one TX key for message decryption
1304 * @tx: TX crypto handle
1305 * @rx: RX crypto handle (can be NULL)
1306 * @skb: the message skb which will be decrypted later
1307 * @tx_key: peer TX key id
1308 *
1309 * This function looks up the existing TX keys and pick one which is suitable
1310 * for the message decryption, that must be a cluster key and not used before
1311 * on the same message (i.e. recursive).
1312 *
1313 * Return: the TX AEAD key handle in case of success, otherwise NULL
1314 */
tipc_crypto_key_pick_tx(struct tipc_crypto * tx,struct tipc_crypto * rx,struct sk_buff * skb,u8 tx_key)1315 static struct tipc_aead *tipc_crypto_key_pick_tx(struct tipc_crypto *tx,
1316 struct tipc_crypto *rx,
1317 struct sk_buff *skb,
1318 u8 tx_key)
1319 {
1320 struct tipc_skb_cb *skb_cb = TIPC_SKB_CB(skb);
1321 struct tipc_aead *aead = NULL;
1322 struct tipc_key key = tx->key;
1323 u8 k, i = 0;
1324
1325 /* Initialize data if not yet */
1326 if (!skb_cb->tx_clone_deferred) {
1327 skb_cb->tx_clone_deferred = 1;
1328 memset(&skb_cb->tx_clone_ctx, 0, sizeof(skb_cb->tx_clone_ctx));
1329 }
1330
1331 skb_cb->tx_clone_ctx.rx = rx;
1332 if (++skb_cb->tx_clone_ctx.recurs > 2)
1333 return NULL;
1334
1335 /* Pick one TX key */
1336 spin_lock(&tx->lock);
1337 if (tx_key == KEY_MASTER) {
1338 aead = tipc_aead_rcu_ptr(tx->aead[KEY_MASTER], &tx->lock);
1339 goto done;
1340 }
1341 do {
1342 k = (i == 0) ? key.pending :
1343 ((i == 1) ? key.active : key.passive);
1344 if (!k)
1345 continue;
1346 aead = tipc_aead_rcu_ptr(tx->aead[k], &tx->lock);
1347 if (!aead)
1348 continue;
1349 if (aead->mode != CLUSTER_KEY ||
1350 aead == skb_cb->tx_clone_ctx.last) {
1351 aead = NULL;
1352 continue;
1353 }
1354 /* Ok, found one cluster key */
1355 skb_cb->tx_clone_ctx.last = aead;
1356 WARN_ON(skb->next);
1357 skb->next = skb_clone(skb, GFP_ATOMIC);
1358 if (unlikely(!skb->next))
1359 pr_warn("Failed to clone skb for next round if any\n");
1360 break;
1361 } while (++i < 3);
1362
1363 done:
1364 if (likely(aead))
1365 WARN_ON(!refcount_inc_not_zero(&aead->refcnt));
1366 spin_unlock(&tx->lock);
1367
1368 return aead;
1369 }
1370
1371 /**
1372 * tipc_crypto_key_synch: Synch own key data according to peer key status
1373 * @rx: RX crypto handle
1374 * @skb: TIPCv2 message buffer (incl. the ehdr from peer)
1375 *
1376 * This function updates the peer node related data as the peer RX active key
1377 * has changed, so the number of TX keys' users on this node are increased and
1378 * decreased correspondingly.
1379 *
1380 * It also considers if peer has no key, then we need to make own master key
1381 * (if any) taking over i.e. starting grace period and also trigger key
1382 * distributing process.
1383 *
1384 * The "per-peer" sndnxt is also reset when the peer key has switched.
1385 */
tipc_crypto_key_synch(struct tipc_crypto * rx,struct sk_buff * skb)1386 static void tipc_crypto_key_synch(struct tipc_crypto *rx, struct sk_buff *skb)
1387 {
1388 struct tipc_ehdr *ehdr = (struct tipc_ehdr *)skb_network_header(skb);
1389 struct tipc_crypto *tx = tipc_net(rx->net)->crypto_tx;
1390 struct tipc_msg *hdr = buf_msg(skb);
1391 u32 self = tipc_own_addr(rx->net);
1392 u8 cur, new;
1393 unsigned long delay;
1394
1395 /* Update RX 'key_master' flag according to peer, also mark "legacy" if
1396 * a peer has no master key.
1397 */
1398 rx->key_master = ehdr->master_key;
1399 if (!rx->key_master)
1400 tx->legacy_user = 1;
1401
1402 /* For later cases, apply only if message is destined to this node */
1403 if (!ehdr->destined || msg_short(hdr) || msg_destnode(hdr) != self)
1404 return;
1405
1406 /* Case 1: Peer has no keys, let's make master key take over */
1407 if (ehdr->rx_nokey) {
1408 /* Set or extend grace period */
1409 tx->timer2 = jiffies;
1410 /* Schedule key distributing for the peer if not yet */
1411 if (tx->key.keys &&
1412 !atomic_cmpxchg(&rx->key_distr, 0, KEY_DISTR_SCHED)) {
1413 get_random_bytes(&delay, 2);
1414 delay %= 5;
1415 delay = msecs_to_jiffies(500 * ++delay);
1416 if (queue_delayed_work(tx->wq, &rx->work, delay))
1417 tipc_node_get(rx->node);
1418 }
1419 } else {
1420 /* Cancel a pending key distributing if any */
1421 atomic_xchg(&rx->key_distr, 0);
1422 }
1423
1424 /* Case 2: Peer RX active key has changed, let's update own TX users */
1425 cur = atomic_read(&rx->peer_rx_active);
1426 new = ehdr->rx_key_active;
1427 if (tx->key.keys &&
1428 cur != new &&
1429 atomic_cmpxchg(&rx->peer_rx_active, cur, new) == cur) {
1430 if (new)
1431 tipc_aead_users_inc(tx->aead[new], INT_MAX);
1432 if (cur)
1433 tipc_aead_users_dec(tx->aead[cur], 0);
1434
1435 atomic64_set(&rx->sndnxt, 0);
1436 /* Mark the point TX key users changed */
1437 tx->timer1 = jiffies;
1438
1439 pr_debug("%s: key users changed %d-- %d++, peer %s\n",
1440 tx->name, cur, new, rx->name);
1441 }
1442 }
1443
tipc_crypto_key_revoke(struct net * net,u8 tx_key)1444 static int tipc_crypto_key_revoke(struct net *net, u8 tx_key)
1445 {
1446 struct tipc_crypto *tx = tipc_net(net)->crypto_tx;
1447 struct tipc_key key;
1448
1449 spin_lock_bh(&tx->lock);
1450 key = tx->key;
1451 WARN_ON(!key.active || tx_key != key.active);
1452
1453 /* Free the active key */
1454 tipc_crypto_key_set_state(tx, key.passive, 0, key.pending);
1455 tipc_crypto_key_detach(tx->aead[key.active], &tx->lock);
1456 spin_unlock_bh(&tx->lock);
1457
1458 pr_warn("%s: key is revoked\n", tx->name);
1459 return -EKEYREVOKED;
1460 }
1461
tipc_crypto_start(struct tipc_crypto ** crypto,struct net * net,struct tipc_node * node)1462 int tipc_crypto_start(struct tipc_crypto **crypto, struct net *net,
1463 struct tipc_node *node)
1464 {
1465 struct tipc_crypto *c;
1466
1467 if (*crypto)
1468 return -EEXIST;
1469
1470 /* Allocate crypto */
1471 c = kzalloc(sizeof(*c), GFP_ATOMIC);
1472 if (!c)
1473 return -ENOMEM;
1474
1475 /* Allocate workqueue on TX */
1476 if (!node) {
1477 c->wq = alloc_ordered_workqueue("tipc_crypto", 0);
1478 if (!c->wq) {
1479 kfree(c);
1480 return -ENOMEM;
1481 }
1482 }
1483
1484 /* Allocate statistic structure */
1485 c->stats = alloc_percpu_gfp(struct tipc_crypto_stats, GFP_ATOMIC);
1486 if (!c->stats) {
1487 if (c->wq)
1488 destroy_workqueue(c->wq);
1489 kfree_sensitive(c);
1490 return -ENOMEM;
1491 }
1492
1493 c->flags = 0;
1494 c->net = net;
1495 c->node = node;
1496 get_random_bytes(&c->key_gen, 2);
1497 tipc_crypto_key_set_state(c, 0, 0, 0);
1498 atomic_set(&c->key_distr, 0);
1499 atomic_set(&c->peer_rx_active, 0);
1500 atomic64_set(&c->sndnxt, 0);
1501 c->timer1 = jiffies;
1502 c->timer2 = jiffies;
1503 c->rekeying_intv = TIPC_REKEYING_INTV_DEF;
1504 spin_lock_init(&c->lock);
1505 scnprintf(c->name, 48, "%s(%s)", (is_rx(c)) ? "RX" : "TX",
1506 (is_rx(c)) ? tipc_node_get_id_str(c->node) :
1507 tipc_own_id_string(c->net));
1508
1509 if (is_rx(c))
1510 INIT_DELAYED_WORK(&c->work, tipc_crypto_work_rx);
1511 else
1512 INIT_DELAYED_WORK(&c->work, tipc_crypto_work_tx);
1513
1514 *crypto = c;
1515 return 0;
1516 }
1517
tipc_crypto_stop(struct tipc_crypto ** crypto)1518 void tipc_crypto_stop(struct tipc_crypto **crypto)
1519 {
1520 struct tipc_crypto *c = *crypto;
1521 u8 k;
1522
1523 if (!c)
1524 return;
1525
1526 /* Flush any queued works & destroy wq */
1527 if (is_tx(c)) {
1528 c->rekeying_intv = 0;
1529 cancel_delayed_work_sync(&c->work);
1530 destroy_workqueue(c->wq);
1531 }
1532
1533 /* Release AEAD keys */
1534 rcu_read_lock();
1535 for (k = KEY_MIN; k <= KEY_MAX; k++)
1536 tipc_aead_put(rcu_dereference(c->aead[k]));
1537 rcu_read_unlock();
1538 pr_debug("%s: has been stopped\n", c->name);
1539
1540 /* Free this crypto statistics */
1541 free_percpu(c->stats);
1542
1543 *crypto = NULL;
1544 kfree_sensitive(c);
1545 }
1546
tipc_crypto_timeout(struct tipc_crypto * rx)1547 void tipc_crypto_timeout(struct tipc_crypto *rx)
1548 {
1549 struct tipc_net *tn = tipc_net(rx->net);
1550 struct tipc_crypto *tx = tn->crypto_tx;
1551 struct tipc_key key;
1552 int cmd;
1553
1554 /* TX pending: taking all users & stable -> active */
1555 spin_lock(&tx->lock);
1556 key = tx->key;
1557 if (key.active && tipc_aead_users(tx->aead[key.active]) > 0)
1558 goto s1;
1559 if (!key.pending || tipc_aead_users(tx->aead[key.pending]) <= 0)
1560 goto s1;
1561 if (time_before(jiffies, tx->timer1 + TIPC_TX_LASTING_TIME))
1562 goto s1;
1563
1564 tipc_crypto_key_set_state(tx, key.passive, key.pending, 0);
1565 if (key.active)
1566 tipc_crypto_key_detach(tx->aead[key.active], &tx->lock);
1567 this_cpu_inc(tx->stats->stat[STAT_SWITCHES]);
1568 pr_info("%s: key[%d] is activated\n", tx->name, key.pending);
1569
1570 s1:
1571 spin_unlock(&tx->lock);
1572
1573 /* RX pending: having user -> active */
1574 spin_lock(&rx->lock);
1575 key = rx->key;
1576 if (!key.pending || tipc_aead_users(rx->aead[key.pending]) <= 0)
1577 goto s2;
1578
1579 if (key.active)
1580 key.passive = key.active;
1581 key.active = key.pending;
1582 rx->timer2 = jiffies;
1583 tipc_crypto_key_set_state(rx, key.passive, key.active, 0);
1584 this_cpu_inc(rx->stats->stat[STAT_SWITCHES]);
1585 pr_info("%s: key[%d] is activated\n", rx->name, key.pending);
1586 goto s5;
1587
1588 s2:
1589 /* RX pending: not working -> remove */
1590 if (!key.pending || tipc_aead_users(rx->aead[key.pending]) > -10)
1591 goto s3;
1592
1593 tipc_crypto_key_set_state(rx, key.passive, key.active, 0);
1594 tipc_crypto_key_detach(rx->aead[key.pending], &rx->lock);
1595 pr_debug("%s: key[%d] is removed\n", rx->name, key.pending);
1596 goto s5;
1597
1598 s3:
1599 /* RX active: timed out or no user -> pending */
1600 if (!key.active)
1601 goto s4;
1602 if (time_before(jiffies, rx->timer1 + TIPC_RX_ACTIVE_LIM) &&
1603 tipc_aead_users(rx->aead[key.active]) > 0)
1604 goto s4;
1605
1606 if (key.pending)
1607 key.passive = key.active;
1608 else
1609 key.pending = key.active;
1610 rx->timer2 = jiffies;
1611 tipc_crypto_key_set_state(rx, key.passive, 0, key.pending);
1612 tipc_aead_users_set(rx->aead[key.pending], 0);
1613 pr_debug("%s: key[%d] is deactivated\n", rx->name, key.active);
1614 goto s5;
1615
1616 s4:
1617 /* RX passive: outdated or not working -> free */
1618 if (!key.passive)
1619 goto s5;
1620 if (time_before(jiffies, rx->timer2 + TIPC_RX_PASSIVE_LIM) &&
1621 tipc_aead_users(rx->aead[key.passive]) > -10)
1622 goto s5;
1623
1624 tipc_crypto_key_set_state(rx, 0, key.active, key.pending);
1625 tipc_crypto_key_detach(rx->aead[key.passive], &rx->lock);
1626 pr_debug("%s: key[%d] is freed\n", rx->name, key.passive);
1627
1628 s5:
1629 spin_unlock(&rx->lock);
1630
1631 /* Relax it here, the flag will be set again if it really is, but only
1632 * when we are not in grace period for safety!
1633 */
1634 if (time_after(jiffies, tx->timer2 + TIPC_TX_GRACE_PERIOD))
1635 tx->legacy_user = 0;
1636
1637 /* Limit max_tfms & do debug commands if needed */
1638 if (likely(sysctl_tipc_max_tfms <= TIPC_MAX_TFMS_LIM))
1639 return;
1640
1641 cmd = sysctl_tipc_max_tfms;
1642 sysctl_tipc_max_tfms = TIPC_MAX_TFMS_DEF;
1643 tipc_crypto_do_cmd(rx->net, cmd);
1644 }
1645
tipc_crypto_clone_msg(struct net * net,struct sk_buff * _skb,struct tipc_bearer * b,struct tipc_media_addr * dst,struct tipc_node * __dnode,u8 type)1646 static inline void tipc_crypto_clone_msg(struct net *net, struct sk_buff *_skb,
1647 struct tipc_bearer *b,
1648 struct tipc_media_addr *dst,
1649 struct tipc_node *__dnode, u8 type)
1650 {
1651 struct sk_buff *skb;
1652
1653 skb = skb_clone(_skb, GFP_ATOMIC);
1654 if (skb) {
1655 TIPC_SKB_CB(skb)->xmit_type = type;
1656 tipc_crypto_xmit(net, &skb, b, dst, __dnode);
1657 if (skb)
1658 b->media->send_msg(net, skb, b, dst);
1659 }
1660 }
1661
1662 /**
1663 * tipc_crypto_xmit - Build & encrypt TIPC message for xmit
1664 * @net: struct net
1665 * @skb: input/output message skb pointer
1666 * @b: bearer used for xmit later
1667 * @dst: destination media address
1668 * @__dnode: destination node for reference if any
1669 *
1670 * First, build an encryption message header on the top of the message, then
1671 * encrypt the original TIPC message by using the pending, master or active
1672 * key with this preference order.
1673 * If the encryption is successful, the encrypted skb is returned directly or
1674 * via the callback.
1675 * Otherwise, the skb is freed!
1676 *
1677 * Return:
1678 * * 0 : the encryption has succeeded (or no encryption)
1679 * * -EINPROGRESS/-EBUSY : the encryption is ongoing, a callback will be made
1680 * * -ENOKEK : the encryption has failed due to no key
1681 * * -EKEYREVOKED : the encryption has failed due to key revoked
1682 * * -ENOMEM : the encryption has failed due to no memory
1683 * * < 0 : the encryption has failed due to other reasons
1684 */
tipc_crypto_xmit(struct net * net,struct sk_buff ** skb,struct tipc_bearer * b,struct tipc_media_addr * dst,struct tipc_node * __dnode)1685 int tipc_crypto_xmit(struct net *net, struct sk_buff **skb,
1686 struct tipc_bearer *b, struct tipc_media_addr *dst,
1687 struct tipc_node *__dnode)
1688 {
1689 struct tipc_crypto *__rx = tipc_node_crypto_rx(__dnode);
1690 struct tipc_crypto *tx = tipc_net(net)->crypto_tx;
1691 struct tipc_crypto_stats __percpu *stats = tx->stats;
1692 struct tipc_msg *hdr = buf_msg(*skb);
1693 struct tipc_key key = tx->key;
1694 struct tipc_aead *aead = NULL;
1695 u32 user = msg_user(hdr);
1696 u32 type = msg_type(hdr);
1697 int rc = -ENOKEY;
1698 u8 tx_key = 0;
1699
1700 /* No encryption? */
1701 if (!tx->working)
1702 return 0;
1703
1704 /* Pending key if peer has active on it or probing time */
1705 if (unlikely(key.pending)) {
1706 tx_key = key.pending;
1707 if (!tx->key_master && !key.active)
1708 goto encrypt;
1709 if (__rx && atomic_read(&__rx->peer_rx_active) == tx_key)
1710 goto encrypt;
1711 if (TIPC_SKB_CB(*skb)->xmit_type == SKB_PROBING) {
1712 pr_debug("%s: probing for key[%d]\n", tx->name,
1713 key.pending);
1714 goto encrypt;
1715 }
1716 if (user == LINK_CONFIG || user == LINK_PROTOCOL)
1717 tipc_crypto_clone_msg(net, *skb, b, dst, __dnode,
1718 SKB_PROBING);
1719 }
1720
1721 /* Master key if this is a *vital* message or in grace period */
1722 if (tx->key_master) {
1723 tx_key = KEY_MASTER;
1724 if (!key.active)
1725 goto encrypt;
1726 if (TIPC_SKB_CB(*skb)->xmit_type == SKB_GRACING) {
1727 pr_debug("%s: gracing for msg (%d %d)\n", tx->name,
1728 user, type);
1729 goto encrypt;
1730 }
1731 if (user == LINK_CONFIG ||
1732 (user == LINK_PROTOCOL && type == RESET_MSG) ||
1733 (user == MSG_CRYPTO && type == KEY_DISTR_MSG) ||
1734 time_before(jiffies, tx->timer2 + TIPC_TX_GRACE_PERIOD)) {
1735 if (__rx && __rx->key_master &&
1736 !atomic_read(&__rx->peer_rx_active))
1737 goto encrypt;
1738 if (!__rx) {
1739 if (likely(!tx->legacy_user))
1740 goto encrypt;
1741 tipc_crypto_clone_msg(net, *skb, b, dst,
1742 __dnode, SKB_GRACING);
1743 }
1744 }
1745 }
1746
1747 /* Else, use the active key if any */
1748 if (likely(key.active)) {
1749 tx_key = key.active;
1750 goto encrypt;
1751 }
1752
1753 goto exit;
1754
1755 encrypt:
1756 aead = tipc_aead_get(tx->aead[tx_key]);
1757 if (unlikely(!aead))
1758 goto exit;
1759 rc = tipc_ehdr_build(net, aead, tx_key, *skb, __rx);
1760 if (likely(rc > 0))
1761 rc = tipc_aead_encrypt(aead, *skb, b, dst, __dnode);
1762
1763 exit:
1764 switch (rc) {
1765 case 0:
1766 this_cpu_inc(stats->stat[STAT_OK]);
1767 break;
1768 case -EINPROGRESS:
1769 case -EBUSY:
1770 this_cpu_inc(stats->stat[STAT_ASYNC]);
1771 *skb = NULL;
1772 return rc;
1773 default:
1774 this_cpu_inc(stats->stat[STAT_NOK]);
1775 if (rc == -ENOKEY)
1776 this_cpu_inc(stats->stat[STAT_NOKEYS]);
1777 else if (rc == -EKEYREVOKED)
1778 this_cpu_inc(stats->stat[STAT_BADKEYS]);
1779 kfree_skb(*skb);
1780 *skb = NULL;
1781 break;
1782 }
1783
1784 tipc_aead_put(aead);
1785 return rc;
1786 }
1787
1788 /**
1789 * tipc_crypto_rcv - Decrypt an encrypted TIPC message from peer
1790 * @net: struct net
1791 * @rx: RX crypto handle
1792 * @skb: input/output message skb pointer
1793 * @b: bearer where the message has been received
1794 *
1795 * If the decryption is successful, the decrypted skb is returned directly or
1796 * as the callback, the encryption header and auth tag will be trimed out
1797 * before forwarding to tipc_rcv() via the tipc_crypto_rcv_complete().
1798 * Otherwise, the skb will be freed!
1799 * Note: RX key(s) can be re-aligned, or in case of no key suitable, TX
1800 * cluster key(s) can be taken for decryption (- recursive).
1801 *
1802 * Return:
1803 * * 0 : the decryption has successfully completed
1804 * * -EINPROGRESS/-EBUSY : the decryption is ongoing, a callback will be made
1805 * * -ENOKEY : the decryption has failed due to no key
1806 * * -EBADMSG : the decryption has failed due to bad message
1807 * * -ENOMEM : the decryption has failed due to no memory
1808 * * < 0 : the decryption has failed due to other reasons
1809 */
tipc_crypto_rcv(struct net * net,struct tipc_crypto * rx,struct sk_buff ** skb,struct tipc_bearer * b)1810 int tipc_crypto_rcv(struct net *net, struct tipc_crypto *rx,
1811 struct sk_buff **skb, struct tipc_bearer *b)
1812 {
1813 struct tipc_crypto *tx = tipc_net(net)->crypto_tx;
1814 struct tipc_crypto_stats __percpu *stats;
1815 struct tipc_aead *aead = NULL;
1816 struct tipc_key key;
1817 int rc = -ENOKEY;
1818 u8 tx_key, n;
1819
1820 tx_key = ((struct tipc_ehdr *)(*skb)->data)->tx_key;
1821
1822 /* New peer?
1823 * Let's try with TX key (i.e. cluster mode) & verify the skb first!
1824 */
1825 if (unlikely(!rx || tx_key == KEY_MASTER))
1826 goto pick_tx;
1827
1828 /* Pick RX key according to TX key if any */
1829 key = rx->key;
1830 if (tx_key == key.active || tx_key == key.pending ||
1831 tx_key == key.passive)
1832 goto decrypt;
1833
1834 /* Unknown key, let's try to align RX key(s) */
1835 if (tipc_crypto_key_try_align(rx, tx_key))
1836 goto decrypt;
1837
1838 pick_tx:
1839 /* No key suitable? Try to pick one from TX... */
1840 aead = tipc_crypto_key_pick_tx(tx, rx, *skb, tx_key);
1841 if (aead)
1842 goto decrypt;
1843 goto exit;
1844
1845 decrypt:
1846 rcu_read_lock();
1847 if (!aead)
1848 aead = tipc_aead_get(rx->aead[tx_key]);
1849 rc = tipc_aead_decrypt(net, aead, *skb, b);
1850 rcu_read_unlock();
1851
1852 exit:
1853 stats = ((rx) ?: tx)->stats;
1854 switch (rc) {
1855 case 0:
1856 this_cpu_inc(stats->stat[STAT_OK]);
1857 break;
1858 case -EINPROGRESS:
1859 case -EBUSY:
1860 this_cpu_inc(stats->stat[STAT_ASYNC]);
1861 *skb = NULL;
1862 return rc;
1863 default:
1864 this_cpu_inc(stats->stat[STAT_NOK]);
1865 if (rc == -ENOKEY) {
1866 kfree_skb(*skb);
1867 *skb = NULL;
1868 if (rx) {
1869 /* Mark rx->nokey only if we dont have a
1870 * pending received session key, nor a newer
1871 * one i.e. in the next slot.
1872 */
1873 n = key_next(tx_key);
1874 rx->nokey = !(rx->skey ||
1875 rcu_access_pointer(rx->aead[n]));
1876 pr_debug_ratelimited("%s: nokey %d, key %d/%x\n",
1877 rx->name, rx->nokey,
1878 tx_key, rx->key.keys);
1879 tipc_node_put(rx->node);
1880 }
1881 this_cpu_inc(stats->stat[STAT_NOKEYS]);
1882 return rc;
1883 } else if (rc == -EBADMSG) {
1884 this_cpu_inc(stats->stat[STAT_BADMSGS]);
1885 }
1886 break;
1887 }
1888
1889 tipc_crypto_rcv_complete(net, aead, b, skb, rc);
1890 return rc;
1891 }
1892
tipc_crypto_rcv_complete(struct net * net,struct tipc_aead * aead,struct tipc_bearer * b,struct sk_buff ** skb,int err)1893 static void tipc_crypto_rcv_complete(struct net *net, struct tipc_aead *aead,
1894 struct tipc_bearer *b,
1895 struct sk_buff **skb, int err)
1896 {
1897 struct tipc_skb_cb *skb_cb = TIPC_SKB_CB(*skb);
1898 struct tipc_crypto *rx = aead->crypto;
1899 struct tipc_aead *tmp = NULL;
1900 struct tipc_ehdr *ehdr;
1901 struct tipc_node *n;
1902
1903 /* Is this completed by TX? */
1904 if (unlikely(is_tx(aead->crypto))) {
1905 rx = skb_cb->tx_clone_ctx.rx;
1906 pr_debug("TX->RX(%s): err %d, aead %p, skb->next %p, flags %x\n",
1907 (rx) ? tipc_node_get_id_str(rx->node) : "-", err, aead,
1908 (*skb)->next, skb_cb->flags);
1909 pr_debug("skb_cb [recurs %d, last %p], tx->aead [%p %p %p]\n",
1910 skb_cb->tx_clone_ctx.recurs, skb_cb->tx_clone_ctx.last,
1911 aead->crypto->aead[1], aead->crypto->aead[2],
1912 aead->crypto->aead[3]);
1913 if (unlikely(err)) {
1914 if (err == -EBADMSG && (*skb)->next)
1915 tipc_rcv(net, (*skb)->next, b);
1916 goto free_skb;
1917 }
1918
1919 if (likely((*skb)->next)) {
1920 kfree_skb((*skb)->next);
1921 (*skb)->next = NULL;
1922 }
1923 ehdr = (struct tipc_ehdr *)(*skb)->data;
1924 if (!rx) {
1925 WARN_ON(ehdr->user != LINK_CONFIG);
1926 n = tipc_node_create(net, 0, ehdr->id, 0xffffu, 0,
1927 true);
1928 rx = tipc_node_crypto_rx(n);
1929 if (unlikely(!rx))
1930 goto free_skb;
1931 }
1932
1933 /* Ignore cloning if it was TX master key */
1934 if (ehdr->tx_key == KEY_MASTER)
1935 goto rcv;
1936 if (tipc_aead_clone(&tmp, aead) < 0)
1937 goto rcv;
1938 WARN_ON(!refcount_inc_not_zero(&tmp->refcnt));
1939 if (tipc_crypto_key_attach(rx, tmp, ehdr->tx_key, false) < 0) {
1940 tipc_aead_free(&tmp->rcu);
1941 goto rcv;
1942 }
1943 tipc_aead_put(aead);
1944 aead = tmp;
1945 }
1946
1947 if (unlikely(err)) {
1948 tipc_aead_users_dec((struct tipc_aead __force __rcu *)aead, INT_MIN);
1949 goto free_skb;
1950 }
1951
1952 /* Set the RX key's user */
1953 tipc_aead_users_set((struct tipc_aead __force __rcu *)aead, 1);
1954
1955 /* Mark this point, RX works */
1956 rx->timer1 = jiffies;
1957
1958 rcv:
1959 /* Remove ehdr & auth. tag prior to tipc_rcv() */
1960 ehdr = (struct tipc_ehdr *)(*skb)->data;
1961
1962 /* Mark this point, RX passive still works */
1963 if (rx->key.passive && ehdr->tx_key == rx->key.passive)
1964 rx->timer2 = jiffies;
1965
1966 skb_reset_network_header(*skb);
1967 skb_pull(*skb, tipc_ehdr_size(ehdr));
1968 if (pskb_trim(*skb, (*skb)->len - aead->authsize))
1969 goto free_skb;
1970
1971 /* Validate TIPCv2 message */
1972 if (unlikely(!tipc_msg_validate(skb))) {
1973 pr_err_ratelimited("Packet dropped after decryption!\n");
1974 goto free_skb;
1975 }
1976
1977 /* Ok, everything's fine, try to synch own keys according to peers' */
1978 tipc_crypto_key_synch(rx, *skb);
1979
1980 /* Re-fetch skb cb as skb might be changed in tipc_msg_validate */
1981 skb_cb = TIPC_SKB_CB(*skb);
1982
1983 /* Mark skb decrypted */
1984 skb_cb->decrypted = 1;
1985
1986 /* Clear clone cxt if any */
1987 if (likely(!skb_cb->tx_clone_deferred))
1988 goto exit;
1989 skb_cb->tx_clone_deferred = 0;
1990 memset(&skb_cb->tx_clone_ctx, 0, sizeof(skb_cb->tx_clone_ctx));
1991 goto exit;
1992
1993 free_skb:
1994 kfree_skb(*skb);
1995 *skb = NULL;
1996
1997 exit:
1998 tipc_aead_put(aead);
1999 if (rx)
2000 tipc_node_put(rx->node);
2001 }
2002
tipc_crypto_do_cmd(struct net * net,int cmd)2003 static void tipc_crypto_do_cmd(struct net *net, int cmd)
2004 {
2005 struct tipc_net *tn = tipc_net(net);
2006 struct tipc_crypto *tx = tn->crypto_tx, *rx;
2007 struct list_head *p;
2008 unsigned int stat;
2009 int i, j, cpu;
2010 char buf[200];
2011
2012 /* Currently only one command is supported */
2013 switch (cmd) {
2014 case 0xfff1:
2015 goto print_stats;
2016 default:
2017 return;
2018 }
2019
2020 print_stats:
2021 /* Print a header */
2022 pr_info("\n=============== TIPC Crypto Statistics ===============\n\n");
2023
2024 /* Print key status */
2025 pr_info("Key status:\n");
2026 pr_info("TX(%7.7s)\n%s", tipc_own_id_string(net),
2027 tipc_crypto_key_dump(tx, buf));
2028
2029 rcu_read_lock();
2030 for (p = tn->node_list.next; p != &tn->node_list; p = p->next) {
2031 rx = tipc_node_crypto_rx_by_list(p);
2032 pr_info("RX(%7.7s)\n%s", tipc_node_get_id_str(rx->node),
2033 tipc_crypto_key_dump(rx, buf));
2034 }
2035 rcu_read_unlock();
2036
2037 /* Print crypto statistics */
2038 for (i = 0, j = 0; i < MAX_STATS; i++)
2039 j += scnprintf(buf + j, 200 - j, "|%11s ", hstats[i]);
2040 pr_info("Counter %s", buf);
2041
2042 memset(buf, '-', 115);
2043 buf[115] = '\0';
2044 pr_info("%s\n", buf);
2045
2046 j = scnprintf(buf, 200, "TX(%7.7s) ", tipc_own_id_string(net));
2047 for_each_possible_cpu(cpu) {
2048 for (i = 0; i < MAX_STATS; i++) {
2049 stat = per_cpu_ptr(tx->stats, cpu)->stat[i];
2050 j += scnprintf(buf + j, 200 - j, "|%11d ", stat);
2051 }
2052 pr_info("%s", buf);
2053 j = scnprintf(buf, 200, "%12s", " ");
2054 }
2055
2056 rcu_read_lock();
2057 for (p = tn->node_list.next; p != &tn->node_list; p = p->next) {
2058 rx = tipc_node_crypto_rx_by_list(p);
2059 j = scnprintf(buf, 200, "RX(%7.7s) ",
2060 tipc_node_get_id_str(rx->node));
2061 for_each_possible_cpu(cpu) {
2062 for (i = 0; i < MAX_STATS; i++) {
2063 stat = per_cpu_ptr(rx->stats, cpu)->stat[i];
2064 j += scnprintf(buf + j, 200 - j, "|%11d ",
2065 stat);
2066 }
2067 pr_info("%s", buf);
2068 j = scnprintf(buf, 200, "%12s", " ");
2069 }
2070 }
2071 rcu_read_unlock();
2072
2073 pr_info("\n======================== Done ========================\n");
2074 }
2075
tipc_crypto_key_dump(struct tipc_crypto * c,char * buf)2076 static char *tipc_crypto_key_dump(struct tipc_crypto *c, char *buf)
2077 {
2078 struct tipc_key key = c->key;
2079 struct tipc_aead *aead;
2080 int k, i = 0;
2081 char *s;
2082
2083 for (k = KEY_MIN; k <= KEY_MAX; k++) {
2084 if (k == KEY_MASTER) {
2085 if (is_rx(c))
2086 continue;
2087 if (time_before(jiffies,
2088 c->timer2 + TIPC_TX_GRACE_PERIOD))
2089 s = "ACT";
2090 else
2091 s = "PAS";
2092 } else {
2093 if (k == key.passive)
2094 s = "PAS";
2095 else if (k == key.active)
2096 s = "ACT";
2097 else if (k == key.pending)
2098 s = "PEN";
2099 else
2100 s = "-";
2101 }
2102 i += scnprintf(buf + i, 200 - i, "\tKey%d: %s", k, s);
2103
2104 rcu_read_lock();
2105 aead = rcu_dereference(c->aead[k]);
2106 if (aead)
2107 i += scnprintf(buf + i, 200 - i,
2108 "{\"0x...%s\", \"%s\"}/%d:%d",
2109 aead->hint,
2110 (aead->mode == CLUSTER_KEY) ? "c" : "p",
2111 atomic_read(&aead->users),
2112 refcount_read(&aead->refcnt));
2113 rcu_read_unlock();
2114 i += scnprintf(buf + i, 200 - i, "\n");
2115 }
2116
2117 if (is_rx(c))
2118 i += scnprintf(buf + i, 200 - i, "\tPeer RX active: %d\n",
2119 atomic_read(&c->peer_rx_active));
2120
2121 return buf;
2122 }
2123
tipc_key_change_dump(struct tipc_key old,struct tipc_key new,char * buf)2124 static char *tipc_key_change_dump(struct tipc_key old, struct tipc_key new,
2125 char *buf)
2126 {
2127 struct tipc_key *key = &old;
2128 int k, i = 0;
2129 char *s;
2130
2131 /* Output format: "[%s %s %s] -> [%s %s %s]", max len = 32 */
2132 again:
2133 i += scnprintf(buf + i, 32 - i, "[");
2134 for (k = KEY_1; k <= KEY_3; k++) {
2135 if (k == key->passive)
2136 s = "pas";
2137 else if (k == key->active)
2138 s = "act";
2139 else if (k == key->pending)
2140 s = "pen";
2141 else
2142 s = "-";
2143 i += scnprintf(buf + i, 32 - i,
2144 (k != KEY_3) ? "%s " : "%s", s);
2145 }
2146 if (key != &new) {
2147 i += scnprintf(buf + i, 32 - i, "] -> ");
2148 key = &new;
2149 goto again;
2150 }
2151 i += scnprintf(buf + i, 32 - i, "]");
2152 return buf;
2153 }
2154
2155 /**
2156 * tipc_crypto_msg_rcv - Common 'MSG_CRYPTO' processing point
2157 * @net: the struct net
2158 * @skb: the receiving message buffer
2159 */
tipc_crypto_msg_rcv(struct net * net,struct sk_buff * skb)2160 void tipc_crypto_msg_rcv(struct net *net, struct sk_buff *skb)
2161 {
2162 struct tipc_crypto *rx;
2163 struct tipc_msg *hdr;
2164
2165 if (unlikely(skb_linearize(skb)))
2166 goto exit;
2167
2168 hdr = buf_msg(skb);
2169 rx = tipc_node_crypto_rx_by_addr(net, msg_prevnode(hdr));
2170 if (unlikely(!rx))
2171 goto exit;
2172
2173 switch (msg_type(hdr)) {
2174 case KEY_DISTR_MSG:
2175 if (tipc_crypto_key_rcv(rx, hdr))
2176 goto exit;
2177 break;
2178 default:
2179 break;
2180 }
2181
2182 tipc_node_put(rx->node);
2183
2184 exit:
2185 kfree_skb(skb);
2186 }
2187
2188 /**
2189 * tipc_crypto_key_distr - Distribute a TX key
2190 * @tx: the TX crypto
2191 * @key: the key's index
2192 * @dest: the destination tipc node, = NULL if distributing to all nodes
2193 *
2194 * Return: 0 in case of success, otherwise < 0
2195 */
tipc_crypto_key_distr(struct tipc_crypto * tx,u8 key,struct tipc_node * dest)2196 int tipc_crypto_key_distr(struct tipc_crypto *tx, u8 key,
2197 struct tipc_node *dest)
2198 {
2199 struct tipc_aead *aead;
2200 u32 dnode = tipc_node_get_addr(dest);
2201 int rc = -ENOKEY;
2202
2203 if (!sysctl_tipc_key_exchange_enabled)
2204 return 0;
2205
2206 if (key) {
2207 rcu_read_lock();
2208 aead = tipc_aead_get(tx->aead[key]);
2209 if (likely(aead)) {
2210 rc = tipc_crypto_key_xmit(tx->net, aead->key,
2211 aead->gen, aead->mode,
2212 dnode);
2213 tipc_aead_put(aead);
2214 }
2215 rcu_read_unlock();
2216 }
2217
2218 return rc;
2219 }
2220
2221 /**
2222 * tipc_crypto_key_xmit - Send a session key
2223 * @net: the struct net
2224 * @skey: the session key to be sent
2225 * @gen: the key's generation
2226 * @mode: the key's mode
2227 * @dnode: the destination node address, = 0 if broadcasting to all nodes
2228 *
2229 * The session key 'skey' is packed in a TIPC v2 'MSG_CRYPTO/KEY_DISTR_MSG'
2230 * as its data section, then xmit-ed through the uc/bc link.
2231 *
2232 * Return: 0 in case of success, otherwise < 0
2233 */
tipc_crypto_key_xmit(struct net * net,struct tipc_aead_key * skey,u16 gen,u8 mode,u32 dnode)2234 static int tipc_crypto_key_xmit(struct net *net, struct tipc_aead_key *skey,
2235 u16 gen, u8 mode, u32 dnode)
2236 {
2237 struct sk_buff_head pkts;
2238 struct tipc_msg *hdr;
2239 struct sk_buff *skb;
2240 u16 size, cong_link_cnt;
2241 u8 *data;
2242 int rc;
2243
2244 size = tipc_aead_key_size(skey);
2245 skb = tipc_buf_acquire(INT_H_SIZE + size, GFP_ATOMIC);
2246 if (!skb)
2247 return -ENOMEM;
2248
2249 hdr = buf_msg(skb);
2250 tipc_msg_init(tipc_own_addr(net), hdr, MSG_CRYPTO, KEY_DISTR_MSG,
2251 INT_H_SIZE, dnode);
2252 msg_set_size(hdr, INT_H_SIZE + size);
2253 msg_set_key_gen(hdr, gen);
2254 msg_set_key_mode(hdr, mode);
2255
2256 data = msg_data(hdr);
2257 *((__be32 *)(data + TIPC_AEAD_ALG_NAME)) = htonl(skey->keylen);
2258 memcpy(data, skey->alg_name, TIPC_AEAD_ALG_NAME);
2259 memcpy(data + TIPC_AEAD_ALG_NAME + sizeof(__be32), skey->key,
2260 skey->keylen);
2261
2262 __skb_queue_head_init(&pkts);
2263 __skb_queue_tail(&pkts, skb);
2264 if (dnode)
2265 rc = tipc_node_xmit(net, &pkts, dnode, 0);
2266 else
2267 rc = tipc_bcast_xmit(net, &pkts, &cong_link_cnt);
2268
2269 return rc;
2270 }
2271
2272 /**
2273 * tipc_crypto_key_rcv - Receive a session key
2274 * @rx: the RX crypto
2275 * @hdr: the TIPC v2 message incl. the receiving session key in its data
2276 *
2277 * This function retrieves the session key in the message from peer, then
2278 * schedules a RX work to attach the key to the corresponding RX crypto.
2279 *
2280 * Return: "true" if the key has been scheduled for attaching, otherwise
2281 * "false".
2282 */
tipc_crypto_key_rcv(struct tipc_crypto * rx,struct tipc_msg * hdr)2283 static bool tipc_crypto_key_rcv(struct tipc_crypto *rx, struct tipc_msg *hdr)
2284 {
2285 struct tipc_crypto *tx = tipc_net(rx->net)->crypto_tx;
2286 struct tipc_aead_key *skey = NULL;
2287 u16 key_gen = msg_key_gen(hdr);
2288 u32 size = msg_data_sz(hdr);
2289 u8 *data = msg_data(hdr);
2290 unsigned int keylen;
2291
2292 /* Verify whether the size can exist in the packet */
2293 if (unlikely(size < sizeof(struct tipc_aead_key) + TIPC_AEAD_KEYLEN_MIN)) {
2294 pr_debug("%s: message data size is too small\n", rx->name);
2295 goto exit;
2296 }
2297
2298 keylen = ntohl(*((__be32 *)(data + TIPC_AEAD_ALG_NAME)));
2299
2300 /* Verify the supplied size values */
2301 if (unlikely(keylen > TIPC_AEAD_KEY_SIZE_MAX ||
2302 size != keylen + sizeof(struct tipc_aead_key))) {
2303 pr_debug("%s: invalid MSG_CRYPTO key size\n", rx->name);
2304 goto exit;
2305 }
2306
2307 spin_lock(&rx->lock);
2308 if (unlikely(rx->skey || (key_gen == rx->key_gen && rx->key.keys))) {
2309 pr_err("%s: key existed <%p>, gen %d vs %d\n", rx->name,
2310 rx->skey, key_gen, rx->key_gen);
2311 goto exit_unlock;
2312 }
2313
2314 /* Allocate memory for the key */
2315 skey = kmalloc(size, GFP_ATOMIC);
2316 if (unlikely(!skey)) {
2317 pr_err("%s: unable to allocate memory for skey\n", rx->name);
2318 goto exit_unlock;
2319 }
2320
2321 /* Copy key from msg data */
2322 skey->keylen = keylen;
2323 memcpy(skey->alg_name, data, TIPC_AEAD_ALG_NAME);
2324 memcpy(skey->key, data + TIPC_AEAD_ALG_NAME + sizeof(__be32),
2325 skey->keylen);
2326
2327 rx->key_gen = key_gen;
2328 rx->skey_mode = msg_key_mode(hdr);
2329 rx->skey = skey;
2330 rx->nokey = 0;
2331 mb(); /* for nokey flag */
2332
2333 exit_unlock:
2334 spin_unlock(&rx->lock);
2335
2336 exit:
2337 /* Schedule the key attaching on this crypto */
2338 if (likely(skey && queue_delayed_work(tx->wq, &rx->work, 0)))
2339 return true;
2340
2341 return false;
2342 }
2343
2344 /**
2345 * tipc_crypto_work_rx - Scheduled RX works handler
2346 * @work: the struct RX work
2347 *
2348 * The function processes the previous scheduled works i.e. distributing TX key
2349 * or attaching a received session key on RX crypto.
2350 */
tipc_crypto_work_rx(struct work_struct * work)2351 static void tipc_crypto_work_rx(struct work_struct *work)
2352 {
2353 struct delayed_work *dwork = to_delayed_work(work);
2354 struct tipc_crypto *rx = container_of(dwork, struct tipc_crypto, work);
2355 struct tipc_crypto *tx = tipc_net(rx->net)->crypto_tx;
2356 unsigned long delay = msecs_to_jiffies(5000);
2357 bool resched = false;
2358 u8 key;
2359 int rc;
2360
2361 /* Case 1: Distribute TX key to peer if scheduled */
2362 if (atomic_cmpxchg(&rx->key_distr,
2363 KEY_DISTR_SCHED,
2364 KEY_DISTR_COMPL) == KEY_DISTR_SCHED) {
2365 /* Always pick the newest one for distributing */
2366 key = tx->key.pending ?: tx->key.active;
2367 rc = tipc_crypto_key_distr(tx, key, rx->node);
2368 if (unlikely(rc))
2369 pr_warn("%s: unable to distr key[%d] to %s, err %d\n",
2370 tx->name, key, tipc_node_get_id_str(rx->node),
2371 rc);
2372
2373 /* Sched for key_distr releasing */
2374 resched = true;
2375 } else {
2376 atomic_cmpxchg(&rx->key_distr, KEY_DISTR_COMPL, 0);
2377 }
2378
2379 /* Case 2: Attach a pending received session key from peer if any */
2380 if (rx->skey) {
2381 rc = tipc_crypto_key_init(rx, rx->skey, rx->skey_mode, false);
2382 if (unlikely(rc < 0))
2383 pr_warn("%s: unable to attach received skey, err %d\n",
2384 rx->name, rc);
2385 switch (rc) {
2386 case -EBUSY:
2387 case -ENOMEM:
2388 /* Resched the key attaching */
2389 resched = true;
2390 break;
2391 default:
2392 synchronize_rcu();
2393 kfree(rx->skey);
2394 rx->skey = NULL;
2395 break;
2396 }
2397 }
2398
2399 if (resched && queue_delayed_work(tx->wq, &rx->work, delay))
2400 return;
2401
2402 tipc_node_put(rx->node);
2403 }
2404
2405 /**
2406 * tipc_crypto_rekeying_sched - (Re)schedule rekeying w/o new interval
2407 * @tx: TX crypto
2408 * @changed: if the rekeying needs to be rescheduled with new interval
2409 * @new_intv: new rekeying interval (when "changed" = true)
2410 */
tipc_crypto_rekeying_sched(struct tipc_crypto * tx,bool changed,u32 new_intv)2411 void tipc_crypto_rekeying_sched(struct tipc_crypto *tx, bool changed,
2412 u32 new_intv)
2413 {
2414 unsigned long delay;
2415 bool now = false;
2416
2417 if (changed) {
2418 if (new_intv == TIPC_REKEYING_NOW)
2419 now = true;
2420 else
2421 tx->rekeying_intv = new_intv;
2422 cancel_delayed_work_sync(&tx->work);
2423 }
2424
2425 if (tx->rekeying_intv || now) {
2426 delay = (now) ? 0 : tx->rekeying_intv * 60 * 1000;
2427 queue_delayed_work(tx->wq, &tx->work, msecs_to_jiffies(delay));
2428 }
2429 }
2430
2431 /**
2432 * tipc_crypto_work_tx - Scheduled TX works handler
2433 * @work: the struct TX work
2434 *
2435 * The function processes the previous scheduled work, i.e. key rekeying, by
2436 * generating a new session key based on current one, then attaching it to the
2437 * TX crypto and finally distributing it to peers. It also re-schedules the
2438 * rekeying if needed.
2439 */
tipc_crypto_work_tx(struct work_struct * work)2440 static void tipc_crypto_work_tx(struct work_struct *work)
2441 {
2442 struct delayed_work *dwork = to_delayed_work(work);
2443 struct tipc_crypto *tx = container_of(dwork, struct tipc_crypto, work);
2444 struct tipc_aead_key *skey = NULL;
2445 struct tipc_key key = tx->key;
2446 struct tipc_aead *aead;
2447 int rc = -ENOMEM;
2448
2449 if (unlikely(key.pending))
2450 goto resched;
2451
2452 /* Take current key as a template */
2453 rcu_read_lock();
2454 aead = rcu_dereference(tx->aead[key.active ?: KEY_MASTER]);
2455 if (unlikely(!aead)) {
2456 rcu_read_unlock();
2457 /* At least one key should exist for securing */
2458 return;
2459 }
2460
2461 /* Lets duplicate it first */
2462 skey = kmemdup(aead->key, tipc_aead_key_size(aead->key), GFP_ATOMIC);
2463 rcu_read_unlock();
2464
2465 /* Now, generate new key, initiate & distribute it */
2466 if (likely(skey)) {
2467 rc = tipc_aead_key_generate(skey) ?:
2468 tipc_crypto_key_init(tx, skey, PER_NODE_KEY, false);
2469 if (likely(rc > 0))
2470 rc = tipc_crypto_key_distr(tx, rc, NULL);
2471 kfree_sensitive(skey);
2472 }
2473
2474 if (unlikely(rc))
2475 pr_warn_ratelimited("%s: rekeying returns %d\n", tx->name, rc);
2476
2477 resched:
2478 /* Re-schedule rekeying if any */
2479 tipc_crypto_rekeying_sched(tx, false, 0);
2480 }
2481