~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/net/tipc/crypto.c

Version: ~ [ linux-6.11-rc3 ] ~ [ linux-6.10.4 ] ~ [ linux-6.9.12 ] ~ [ linux-6.8.12 ] ~ [ linux-6.7.12 ] ~ [ linux-6.6.45 ] ~ [ linux-6.5.13 ] ~ [ linux-6.4.16 ] ~ [ linux-6.3.13 ] ~ [ linux-6.2.16 ] ~ [ linux-6.1.104 ] ~ [ linux-6.0.19 ] ~ [ linux-5.19.17 ] ~ [ linux-5.18.19 ] ~ [ linux-5.17.15 ] ~ [ linux-5.16.20 ] ~ [ linux-5.15.164 ] ~ [ linux-5.14.21 ] ~ [ linux-5.13.19 ] ~ [ linux-5.12.19 ] ~ [ linux-5.11.22 ] ~ [ linux-5.10.223 ] ~ [ linux-5.9.16 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.281 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.319 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.336 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.337 ] ~ [ linux-4.4.302 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.9 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

Diff markup

Differences between /net/tipc/crypto.c (Version linux-6.11-rc3) and /net/tipc/crypto.c (Version linux-5.10.223)


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

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

sflogo.php