Whamcloud - gitweb
LU-9795 gss: properly handle mgssec
[fs/lustre-release.git] / lustre / ptlrpc / gss / gss_sk_mech.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (C) 2013, 2015, Trustees of Indiana University
24  *
25  * Copyright (c) 2014, 2016, Intel Corporation.
26  *
27  * Author: Jeremy Filizetti <jfilizet@iu.edu>
28  * Author: Andrew Korty <ajk@iu.edu>
29  */
30
31 #define DEBUG_SUBSYSTEM S_SEC
32 #include <linux/init.h>
33 #include <linux/module.h>
34 #include <linux/slab.h>
35 #include <linux/crypto.h>
36 #include <linux/mutex.h>
37 #include <crypto/ctr.h>
38
39 #include <obd.h>
40 #include <obd_class.h>
41 #include <obd_support.h>
42
43 #include "gss_err.h"
44 #include "gss_crypto.h"
45 #include "gss_internal.h"
46 #include "gss_api.h"
47 #include "gss_asn1.h"
48
49 #define SK_INTERFACE_VERSION 1
50 #define SK_MSG_VERSION 1
51 #define SK_MIN_SIZE 8
52 #define SK_IV_SIZE 16
53
54 /* Starting number for reverse contexts.  It is critical to security
55  * that reverse contexts use a different range of numbers than regular
56  * contexts because they are using the same key.  Therefore the IV/nonce
57  * combination must be unique for them.  To accomplish this reverse contexts
58  * use the the negative range of a 64-bit number and regular contexts use the
59  * postive range.  If the same IV/nonce combination were reused it would leak
60  * information about the plaintext. */
61 #define SK_IV_REV_START (1ULL << 63)
62
63 struct sk_ctx {
64         enum cfs_crypto_crypt_alg sc_crypt;
65         enum cfs_crypto_hash_alg  sc_hmac;
66         __u32                     sc_expire;
67         __u32                     sc_host_random;
68         __u32                     sc_peer_random;
69         atomic64_t                sc_iv;
70         rawobj_t                  sc_hmac_key;
71         struct gss_keyblock       sc_session_kb;
72 };
73
74 struct sk_hdr {
75         __u64                   skh_version;
76         __u64                   skh_iv;
77 } __attribute__((packed));
78
79 /* The format of SK wire data is similar to that of RFC3686 ESP Payload
80  * (section 3) except instead of just an IV there is a struct sk_hdr.
81  * ---------------------------------------------------------------------
82  * | struct sk_hdr | ciphertext (variable size) | HMAC (variable size) |
83  * --------------------------------------------------------------------- */
84 struct sk_wire {
85         rawobj_t                skw_header;
86         rawobj_t                skw_cipher;
87         rawobj_t                skw_hmac;
88 };
89
90 static inline unsigned long sk_block_mask(unsigned long len, int blocksize)
91 {
92         return (len + blocksize - 1) & (~(blocksize - 1));
93 }
94
95 static int sk_fill_header(struct sk_ctx *skc, struct sk_hdr *skh)
96 {
97         __u64 tmp_iv;
98         skh->skh_version = be64_to_cpu(SK_MSG_VERSION);
99
100         /* Always using inc_return so we don't use our initial numbers which
101          * could be the reuse detecting numbers */
102         tmp_iv = atomic64_inc_return(&skc->sc_iv);
103         skh->skh_iv = be64_to_cpu(tmp_iv);
104         if (tmp_iv == 0 || tmp_iv == SK_IV_REV_START) {
105                 CERROR("Counter looped, connection must be reset to avoid "
106                        "plaintext information\n");
107                 return GSS_S_FAILURE;
108         }
109
110         return GSS_S_COMPLETE;
111 }
112
113 static int sk_verify_header(struct sk_hdr *skh)
114 {
115         if (cpu_to_be64(skh->skh_version) != SK_MSG_VERSION)
116                 return GSS_S_DEFECTIVE_TOKEN;
117
118         return GSS_S_COMPLETE;
119 }
120
121 void sk_construct_rfc3686_iv(__u8 *iv, __u32 nonce, __u64 partial_iv)
122 {
123         __u32 ctr = cpu_to_be32(1);
124
125         memcpy(iv, &nonce, CTR_RFC3686_NONCE_SIZE);
126         iv += CTR_RFC3686_NONCE_SIZE;
127         memcpy(iv, &partial_iv, CTR_RFC3686_IV_SIZE);
128         iv += CTR_RFC3686_IV_SIZE;
129         memcpy(iv, &ctr, sizeof(ctr));
130 }
131
132 static int sk_fill_context(rawobj_t *inbuf, struct sk_ctx *skc)
133 {
134         char *ptr = inbuf->data;
135         char *end = inbuf->data + inbuf->len;
136         char sk_hmac[CRYPTO_MAX_ALG_NAME];
137         char sk_crypt[CRYPTO_MAX_ALG_NAME];
138         u32 tmp;
139
140         /* see sk_serialize_kctx() for format from userspace side */
141         /*  1. Version */
142         if (gss_get_bytes(&ptr, end, &tmp, sizeof(tmp))) {
143                 CERROR("Failed to read shared key interface version\n");
144                 return -1;
145         }
146         if (tmp != SK_INTERFACE_VERSION) {
147                 CERROR("Invalid shared key interface version: %d\n", tmp);
148                 return -1;
149         }
150
151         /* 2. HMAC type */
152         if (gss_get_bytes(&ptr, end, &sk_hmac, sizeof(sk_hmac))) {
153                 CERROR("Failed to read HMAC algorithm type\n");
154                 return -1;
155         }
156
157         skc->sc_hmac = cfs_crypto_hash_alg(sk_hmac);
158         if (skc->sc_hmac != CFS_HASH_ALG_NULL &&
159             skc->sc_hmac != CFS_HASH_ALG_SHA256 &&
160             skc->sc_hmac != CFS_HASH_ALG_SHA512) {
161                 CERROR("Invalid hmac type: %s\n", sk_hmac);
162                 return -1;
163         }
164
165         /* 3. crypt type */
166         if (gss_get_bytes(&ptr, end, &sk_crypt, sizeof(sk_crypt))) {
167                 CERROR("Failed to read crypt algorithm type\n");
168                 return -1;
169         }
170
171         skc->sc_crypt = cfs_crypto_crypt_alg(sk_crypt);
172         if (skc->sc_crypt == CFS_CRYPT_ALG_UNKNOWN) {
173                 CERROR("Invalid crypt type: %s\n", sk_crypt);
174                 return -1;
175         }
176
177         /* 4. expiration time */
178         if (gss_get_bytes(&ptr, end, &tmp, sizeof(tmp))) {
179                 CERROR("Failed to read context expiration time\n");
180                 return -1;
181         }
182         skc->sc_expire = tmp + ktime_get_real_seconds();
183
184         /* 5. host random is used as nonce for encryption */
185         if (gss_get_bytes(&ptr, end, &skc->sc_host_random,
186                           sizeof(skc->sc_host_random))) {
187                 CERROR("Failed to read host random\n");
188                 return -1;
189         }
190
191         /* 6. peer random is used as nonce for decryption */
192         if (gss_get_bytes(&ptr, end, &skc->sc_peer_random,
193                           sizeof(skc->sc_peer_random))) {
194                 CERROR("Failed to read peer random\n");
195                 return -1;
196         }
197
198         /* 7. HMAC key */
199         if (gss_get_rawobj(&ptr, end, &skc->sc_hmac_key)) {
200                 CERROR("Failed to read HMAC key\n");
201                 return -1;
202         }
203         if (skc->sc_hmac_key.len <= SK_MIN_SIZE) {
204                 CERROR("HMAC key must key must be larger than %d bytes\n",
205                        SK_MIN_SIZE);
206                 return -1;
207         }
208
209         /* 8. Session key, can be empty if not using privacy mode */
210         if (gss_get_rawobj(&ptr, end, &skc->sc_session_kb.kb_key)) {
211                 CERROR("Failed to read session key\n");
212                 return -1;
213         }
214
215         return 0;
216 }
217
218 static void sk_delete_context(struct sk_ctx *skc)
219 {
220         if (!skc)
221                 return;
222
223         rawobj_free(&skc->sc_hmac_key);
224         gss_keyblock_free(&skc->sc_session_kb);
225         OBD_FREE_PTR(skc);
226 }
227
228 static
229 __u32 gss_import_sec_context_sk(rawobj_t *inbuf, struct gss_ctx *gss_context)
230 {
231         struct sk_ctx *skc;
232         bool privacy = false;
233
234         if (inbuf == NULL || inbuf->data == NULL)
235                 return GSS_S_FAILURE;
236
237         OBD_ALLOC_PTR(skc);
238         if (!skc)
239                 return GSS_S_FAILURE;
240
241         atomic64_set(&skc->sc_iv, 0);
242
243         if (sk_fill_context(inbuf, skc))
244                 goto out_err;
245
246         /* Only privacy mode needs to initialize keys */
247         if (skc->sc_session_kb.kb_key.len > 0) {
248                 privacy = true;
249                 if (gss_keyblock_init(&skc->sc_session_kb,
250                                       cfs_crypto_crypt_name(skc->sc_crypt), 0))
251                         goto out_err;
252         }
253
254         gss_context->internal_ctx_id = skc;
255         CDEBUG(D_SEC, "successfully imported sk%s context\n",
256                privacy ? " (with privacy)" : "");
257
258         return GSS_S_COMPLETE;
259
260 out_err:
261         sk_delete_context(skc);
262         return GSS_S_FAILURE;
263 }
264
265 static
266 __u32 gss_copy_reverse_context_sk(struct gss_ctx *gss_context_old,
267                                   struct gss_ctx *gss_context_new)
268 {
269         struct sk_ctx *skc_old = gss_context_old->internal_ctx_id;
270         struct sk_ctx *skc_new;
271
272         OBD_ALLOC_PTR(skc_new);
273         if (!skc_new)
274                 return GSS_S_FAILURE;
275
276         skc_new->sc_hmac = skc_old->sc_hmac;
277         skc_new->sc_crypt = skc_old->sc_crypt;
278         skc_new->sc_expire = skc_old->sc_expire;
279         skc_new->sc_host_random = skc_old->sc_host_random;
280         skc_new->sc_peer_random = skc_old->sc_peer_random;
281
282         atomic64_set(&skc_new->sc_iv, SK_IV_REV_START);
283
284         if (rawobj_dup(&skc_new->sc_hmac_key, &skc_old->sc_hmac_key))
285                 goto out_err;
286         if (gss_keyblock_dup(&skc_new->sc_session_kb, &skc_old->sc_session_kb))
287                 goto out_err;
288
289         /* Only privacy mode needs to initialize keys */
290         if (skc_new->sc_session_kb.kb_key.len > 0)
291                 if (gss_keyblock_init(&skc_new->sc_session_kb,
292                                       cfs_crypto_crypt_name(skc_new->sc_crypt),
293                                       0))
294                         goto out_err;
295
296         gss_context_new->internal_ctx_id = skc_new;
297         CDEBUG(D_SEC, "successfully copied reverse sk context\n");
298
299         return GSS_S_COMPLETE;
300
301 out_err:
302         sk_delete_context(skc_new);
303         return GSS_S_FAILURE;
304 }
305
306 static
307 __u32 gss_inquire_context_sk(struct gss_ctx *gss_context,
308                              time64_t *endtime)
309 {
310         struct sk_ctx *skc = gss_context->internal_ctx_id;
311
312         *endtime = skc->sc_expire;
313         return GSS_S_COMPLETE;
314 }
315
316 static
317 u32 sk_make_hmac(enum cfs_crypto_hash_alg algo, rawobj_t *key, int msg_count,
318                  rawobj_t *msgs, int iov_count, lnet_kiov_t *iovs,
319                  rawobj_t *token)
320 {
321         struct ahash_request *req;
322         int rc2, rc;
323
324         req = cfs_crypto_hash_init(algo, key->data, key->len);
325         if (IS_ERR(req)) {
326                 rc = PTR_ERR(req);
327                 goto out_init_failed;
328         }
329
330         rc2 = gss_digest_hash(req, NULL, msg_count, msgs, iov_count, iovs,
331                               token);
332         rc = cfs_crypto_hash_final(req, key->data, &key->len);
333         if (!rc && rc2)
334                 rc = rc2;
335 out_init_failed:
336         return rc ? GSS_S_FAILURE : GSS_S_COMPLETE;
337 }
338
339 static
340 __u32 gss_get_mic_sk(struct gss_ctx *gss_context,
341                      int message_count,
342                      rawobj_t *messages,
343                      int iov_count,
344                      lnet_kiov_t *iovs,
345                      rawobj_t *token)
346 {
347         struct sk_ctx *skc = gss_context->internal_ctx_id;
348
349         return sk_make_hmac(skc->sc_hmac,
350                             &skc->sc_hmac_key, message_count, messages,
351                             iov_count, iovs, token);
352 }
353
354 static
355 u32 sk_verify_hmac(enum cfs_crypto_hash_alg algo, rawobj_t *key,
356                    int message_count, rawobj_t *messages,
357                    int iov_count, lnet_kiov_t *iovs,
358                    rawobj_t *token)
359 {
360         rawobj_t checksum = RAWOBJ_EMPTY;
361         __u32 rc = GSS_S_FAILURE;
362
363         checksum.len = cfs_crypto_hash_digestsize(algo);
364         if (token->len < checksum.len) {
365                 CDEBUG(D_SEC, "Token received too short, expected %d "
366                        "received %d\n", token->len, checksum.len);
367                 return GSS_S_DEFECTIVE_TOKEN;
368         }
369
370         OBD_ALLOC_LARGE(checksum.data, checksum.len);
371         if (!checksum.data)
372                 return rc;
373
374         if (sk_make_hmac(algo, key, message_count,
375                          messages, iov_count, iovs, &checksum)) {
376                 CDEBUG(D_SEC, "Failed to create checksum to validate\n");
377                 goto cleanup;
378         }
379
380         if (memcmp(token->data, checksum.data, checksum.len)) {
381                 CERROR("checksum mismatch\n");
382                 rc = GSS_S_BAD_SIG;
383                 goto cleanup;
384         }
385
386         rc = GSS_S_COMPLETE;
387
388 cleanup:
389         OBD_FREE(checksum.data, checksum.len);
390         return rc;
391 }
392
393 /* sk_verify_bulk_hmac() differs slightly from sk_verify_hmac() because all
394  * encrypted pages in the bulk descriptor are populated although we only need
395  * to decrypt up to the number of bytes actually specified from the sender
396  * (bd_nob) otherwise the calulated HMAC will be incorrect. */
397 static
398 u32 sk_verify_bulk_hmac(enum cfs_crypto_hash_alg sc_hmac, rawobj_t *key,
399                         int msgcnt, rawobj_t *msgs, int iovcnt,
400                         lnet_kiov_t *iovs, int iov_bytes, rawobj_t *token)
401 {
402         rawobj_t checksum = RAWOBJ_EMPTY;
403         struct ahash_request *req;
404         struct scatterlist sg[1];
405         int rc = GSS_S_FAILURE;
406         struct sg_table sgt;
407         int bytes;
408         int i;
409
410         checksum.len = cfs_crypto_hash_digestsize(sc_hmac);
411         if (token->len < checksum.len) {
412                 CDEBUG(D_SEC, "Token received too short, expected %d "
413                        "received %d\n", token->len, checksum.len);
414                 return GSS_S_DEFECTIVE_TOKEN;
415         }
416
417         OBD_ALLOC_LARGE(checksum.data, checksum.len);
418         if (!checksum.data)
419                 return rc;
420
421         req = cfs_crypto_hash_init(sc_hmac, key->data, key->len);
422         if (IS_ERR(req))
423                 goto cleanup;
424
425         for (i = 0; i < msgcnt; i++) {
426                 if (!msgs[i].len)
427                         continue;
428
429                 rc = gss_setup_sgtable(&sgt, sg, msgs[i].data, msgs[i].len);
430                 if (rc != 0)
431                         goto hash_cleanup;
432
433                 ahash_request_set_crypt(req, sg, NULL, msgs[i].len);
434                 rc = crypto_ahash_update(req);
435                 if (rc) {
436                         gss_teardown_sgtable(&sgt);
437                         goto hash_cleanup;
438                 }
439
440                 gss_teardown_sgtable(&sgt);
441         }
442
443         for (i = 0; i < iovcnt && iov_bytes > 0; i++) {
444                 if (iovs[i].kiov_len == 0)
445                         continue;
446
447                 bytes = min_t(int, iov_bytes, iovs[i].kiov_len);
448                 iov_bytes -= bytes;
449
450                 sg_init_table(sg, 1);
451                 sg_set_page(&sg[0], iovs[i].kiov_page, bytes,
452                             iovs[i].kiov_offset);
453                 ahash_request_set_crypt(req, sg, NULL, bytes);
454                 rc = crypto_ahash_update(req);
455                 if (rc)
456                         goto hash_cleanup;
457         }
458
459         if (memcmp(token->data, checksum.data, checksum.len)) {
460                 rc = GSS_S_BAD_SIG;
461                 goto hash_cleanup;
462         }
463
464         rc = GSS_S_COMPLETE;
465
466 hash_cleanup:
467         cfs_crypto_hash_final(req, checksum.data, &checksum.len);
468
469 cleanup:
470         OBD_FREE_LARGE(checksum.data, checksum.len);
471
472         return rc;
473 }
474
475 static
476 __u32 gss_verify_mic_sk(struct gss_ctx *gss_context,
477                         int message_count,
478                         rawobj_t *messages,
479                         int iov_count,
480                         lnet_kiov_t *iovs,
481                         rawobj_t *token)
482 {
483         struct sk_ctx *skc = gss_context->internal_ctx_id;
484
485         return sk_verify_hmac(skc->sc_hmac, &skc->sc_hmac_key,
486                               message_count, messages, iov_count, iovs, token);
487 }
488
489 static
490 __u32 gss_wrap_sk(struct gss_ctx *gss_context, rawobj_t *gss_header,
491                     rawobj_t *message, int message_buffer_length,
492                     rawobj_t *token)
493 {
494         struct sk_ctx *skc = gss_context->internal_ctx_id;
495         size_t sht_bytes = cfs_crypto_hash_digestsize(skc->sc_hmac);
496         struct sk_wire skw;
497         struct sk_hdr skh;
498         rawobj_t msgbufs[3];
499         __u8 local_iv[SK_IV_SIZE];
500         unsigned int blocksize;
501
502         LASSERT(skc->sc_session_kb.kb_tfm);
503
504         blocksize = crypto_blkcipher_blocksize(skc->sc_session_kb.kb_tfm);
505         if (gss_add_padding(message, message_buffer_length, blocksize))
506                 return GSS_S_FAILURE;
507
508         memset(token->data, 0, token->len);
509
510         if (sk_fill_header(skc, &skh) != GSS_S_COMPLETE)
511                 return GSS_S_FAILURE;
512
513         skw.skw_header.data = token->data;
514         skw.skw_header.len = sizeof(skh);
515         memcpy(skw.skw_header.data, &skh, sizeof(skh));
516
517         sk_construct_rfc3686_iv(local_iv, skc->sc_host_random, skh.skh_iv);
518         skw.skw_cipher.data = skw.skw_header.data + skw.skw_header.len;
519         skw.skw_cipher.len = token->len - skw.skw_header.len - sht_bytes;
520         if (gss_crypt_rawobjs(skc->sc_session_kb.kb_tfm, local_iv, 1, message,
521                               &skw.skw_cipher, 1))
522                 return GSS_S_FAILURE;
523
524         /* HMAC covers the SK header, GSS header, and ciphertext */
525         msgbufs[0] = skw.skw_header;
526         msgbufs[1] = *gss_header;
527         msgbufs[2] = skw.skw_cipher;
528
529         skw.skw_hmac.data = skw.skw_cipher.data + skw.skw_cipher.len;
530         skw.skw_hmac.len = sht_bytes;
531         if (sk_make_hmac(skc->sc_hmac, &skc->sc_hmac_key,
532                          3, msgbufs, 0, NULL, &skw.skw_hmac))
533                 return GSS_S_FAILURE;
534
535         token->len = skw.skw_header.len + skw.skw_cipher.len + skw.skw_hmac.len;
536
537         return GSS_S_COMPLETE;
538 }
539
540 static
541 __u32 gss_unwrap_sk(struct gss_ctx *gss_context, rawobj_t *gss_header,
542                       rawobj_t *token, rawobj_t *message)
543 {
544         struct sk_ctx *skc = gss_context->internal_ctx_id;
545         size_t sht_bytes = cfs_crypto_hash_digestsize(skc->sc_hmac);
546         struct sk_wire skw;
547         struct sk_hdr *skh;
548         rawobj_t msgbufs[3];
549         __u8 local_iv[SK_IV_SIZE];
550         unsigned int blocksize;
551         int rc;
552
553         LASSERT(skc->sc_session_kb.kb_tfm);
554
555         if (token->len < sizeof(skh) + sht_bytes)
556                 return GSS_S_DEFECTIVE_TOKEN;
557
558         skw.skw_header.data = token->data;
559         skw.skw_header.len = sizeof(struct sk_hdr);
560         skw.skw_cipher.data = skw.skw_header.data + skw.skw_header.len;
561         skw.skw_cipher.len = token->len - skw.skw_header.len - sht_bytes;
562         skw.skw_hmac.data = skw.skw_cipher.data + skw.skw_cipher.len;
563         skw.skw_hmac.len = sht_bytes;
564
565         blocksize = crypto_blkcipher_blocksize(skc->sc_session_kb.kb_tfm);
566         if (skw.skw_cipher.len % blocksize != 0)
567                 return GSS_S_DEFECTIVE_TOKEN;
568
569         skh = (struct sk_hdr *)skw.skw_header.data;
570         rc = sk_verify_header(skh);
571         if (rc != GSS_S_COMPLETE)
572                 return rc;
573
574         /* HMAC covers the SK header, GSS header, and ciphertext */
575         msgbufs[0] = skw.skw_header;
576         msgbufs[1] = *gss_header;
577         msgbufs[2] = skw.skw_cipher;
578         rc = sk_verify_hmac(skc->sc_hmac, &skc->sc_hmac_key, 3, msgbufs,
579                             0, NULL, &skw.skw_hmac);
580         if (rc)
581                 return rc;
582
583         sk_construct_rfc3686_iv(local_iv, skc->sc_peer_random, skh->skh_iv);
584         message->len = skw.skw_cipher.len;
585         if (gss_crypt_rawobjs(skc->sc_session_kb.kb_tfm, local_iv,
586                               1, &skw.skw_cipher, message, 0))
587                 return GSS_S_FAILURE;
588
589         return GSS_S_COMPLETE;
590 }
591
592 static
593 __u32 gss_prep_bulk_sk(struct gss_ctx *gss_context,
594                        struct ptlrpc_bulk_desc *desc)
595 {
596         struct sk_ctx *skc = gss_context->internal_ctx_id;
597         int blocksize;
598         int i;
599
600         LASSERT(skc->sc_session_kb.kb_tfm);
601         blocksize = crypto_blkcipher_blocksize(skc->sc_session_kb.kb_tfm);
602
603         for (i = 0; i < desc->bd_iov_count; i++) {
604                 if (BD_GET_KIOV(desc, i).kiov_offset & blocksize) {
605                         CERROR("offset %d not blocksize aligned\n",
606                                BD_GET_KIOV(desc, i).kiov_offset);
607                         return GSS_S_FAILURE;
608                 }
609
610                 BD_GET_ENC_KIOV(desc, i).kiov_offset =
611                         BD_GET_KIOV(desc, i).kiov_offset;
612                 BD_GET_ENC_KIOV(desc, i).kiov_len =
613                         sk_block_mask(BD_GET_KIOV(desc, i).kiov_len, blocksize);
614         }
615
616         return GSS_S_COMPLETE;
617 }
618
619 static __u32 sk_encrypt_bulk(struct crypto_blkcipher *tfm, __u8 *iv,
620                              struct ptlrpc_bulk_desc *desc, rawobj_t *cipher,
621                              int adj_nob)
622 {
623         struct blkcipher_desc cdesc = {
624                 .tfm = tfm,
625                 .info = iv,
626                 .flags = 0,
627         };
628         struct scatterlist ptxt;
629         struct scatterlist ctxt;
630         int blocksize;
631         int i;
632         int rc;
633         int nob = 0;
634
635         blocksize = crypto_blkcipher_blocksize(tfm);
636
637         sg_init_table(&ptxt, 1);
638         sg_init_table(&ctxt, 1);
639
640         for (i = 0; i < desc->bd_iov_count; i++) {
641                 sg_set_page(&ptxt, BD_GET_KIOV(desc, i).kiov_page,
642                             sk_block_mask(BD_GET_KIOV(desc, i).kiov_len,
643                                           blocksize),
644                             BD_GET_KIOV(desc, i).kiov_offset);
645                 nob += ptxt.length;
646
647                 sg_set_page(&ctxt, BD_GET_ENC_KIOV(desc, i).kiov_page,
648                             ptxt.length, ptxt.offset);
649
650                 BD_GET_ENC_KIOV(desc, i).kiov_offset = ctxt.offset;
651                 BD_GET_ENC_KIOV(desc, i).kiov_len = ctxt.length;
652
653                 rc = crypto_blkcipher_encrypt_iv(&cdesc, &ctxt, &ptxt,
654                                                  ptxt.length);
655                 if (rc) {
656                         CERROR("failed to encrypt page: %d\n", rc);
657                         return rc;
658                 }
659         }
660
661         if (adj_nob)
662                 desc->bd_nob = nob;
663
664         return 0;
665 }
666
667 static __u32 sk_decrypt_bulk(struct crypto_blkcipher *tfm, __u8 *iv,
668                              struct ptlrpc_bulk_desc *desc, rawobj_t *cipher,
669                              int adj_nob)
670 {
671         struct blkcipher_desc cdesc = {
672                 .tfm = tfm,
673                 .info = iv,
674                 .flags = 0,
675         };
676         struct scatterlist ptxt;
677         struct scatterlist ctxt;
678         int blocksize;
679         int i;
680         int rc;
681         int pnob = 0;
682         int cnob = 0;
683
684         sg_init_table(&ptxt, 1);
685         sg_init_table(&ctxt, 1);
686
687         blocksize = crypto_blkcipher_blocksize(tfm);
688         if (desc->bd_nob_transferred % blocksize != 0) {
689                 CERROR("Transfer not a multiple of block size: %d\n",
690                        desc->bd_nob_transferred);
691                 return GSS_S_DEFECTIVE_TOKEN;
692         }
693
694         for (i = 0; i < desc->bd_iov_count && cnob < desc->bd_nob_transferred;
695              i++) {
696                 lnet_kiov_t *piov = &BD_GET_KIOV(desc, i);
697                 lnet_kiov_t *ciov = &BD_GET_ENC_KIOV(desc, i);
698
699                 if (ciov->kiov_offset % blocksize != 0 ||
700                     ciov->kiov_len % blocksize != 0) {
701                         CERROR("Invalid bulk descriptor vector\n");
702                         return GSS_S_DEFECTIVE_TOKEN;
703                 }
704
705                 /* Must adjust bytes here because we know the actual sizes after
706                  * decryption.  Similar to what gss_cli_ctx_unwrap_bulk does for
707                  * integrity only mode */
708                 if (adj_nob) {
709                         /* cipher text must not exceed transferred size */
710                         if (ciov->kiov_len + cnob > desc->bd_nob_transferred)
711                                 ciov->kiov_len =
712                                         desc->bd_nob_transferred - cnob;
713
714                         piov->kiov_len = ciov->kiov_len;
715
716                         /* plain text must not exceed bulk's size */
717                         if (ciov->kiov_len + pnob > desc->bd_nob)
718                                 piov->kiov_len = desc->bd_nob - pnob;
719                 } else {
720                         /* Taken from krb5_decrypt since it was not verified
721                          * whether or not LNET guarantees these */
722                         if (ciov->kiov_len + cnob > desc->bd_nob_transferred ||
723                             piov->kiov_len > ciov->kiov_len) {
724                                 CERROR("Invalid decrypted length\n");
725                                 return GSS_S_FAILURE;
726                         }
727                 }
728
729                 if (ciov->kiov_len == 0)
730                         continue;
731
732                 sg_init_table(&ctxt, 1);
733                 sg_set_page(&ctxt, ciov->kiov_page, ciov->kiov_len,
734                             ciov->kiov_offset);
735                 ptxt = ctxt;
736
737                 /* In the event the plain text size is not a multiple
738                  * of blocksize we decrypt in place and copy the result
739                  * after the decryption */
740                 if (piov->kiov_len % blocksize == 0)
741                         sg_assign_page(&ptxt, piov->kiov_page);
742
743                 rc = crypto_blkcipher_decrypt_iv(&cdesc, &ptxt, &ctxt,
744                                                  ctxt.length);
745                 if (rc) {
746                         CERROR("Decryption failed for page: %d\n", rc);
747                         return GSS_S_FAILURE;
748                 }
749
750                 if (piov->kiov_len % blocksize != 0) {
751                         memcpy(page_address(piov->kiov_page) +
752                                piov->kiov_offset,
753                                page_address(ciov->kiov_page) +
754                                ciov->kiov_offset,
755                                piov->kiov_len);
756                 }
757
758                 cnob += ciov->kiov_len;
759                 pnob += piov->kiov_len;
760         }
761
762         /* if needed, clear up the rest unused iovs */
763         if (adj_nob)
764                 while (i < desc->bd_iov_count)
765                         BD_GET_KIOV(desc, i++).kiov_len = 0;
766
767         if (unlikely(cnob != desc->bd_nob_transferred)) {
768                 CERROR("%d cipher text transferred but only %d decrypted\n",
769                        desc->bd_nob_transferred, cnob);
770                 return GSS_S_FAILURE;
771         }
772
773         if (unlikely(!adj_nob && pnob != desc->bd_nob)) {
774                 CERROR("%d plain text expected but only %d received\n",
775                        desc->bd_nob, pnob);
776                 return GSS_S_FAILURE;
777         }
778
779         return 0;
780 }
781
782 static
783 __u32 gss_wrap_bulk_sk(struct gss_ctx *gss_context,
784                        struct ptlrpc_bulk_desc *desc, rawobj_t *token,
785                        int adj_nob)
786 {
787         struct sk_ctx *skc = gss_context->internal_ctx_id;
788         size_t sht_bytes = cfs_crypto_hash_digestsize(skc->sc_hmac);
789         struct sk_wire skw;
790         struct sk_hdr skh;
791         __u8 local_iv[SK_IV_SIZE];
792
793         LASSERT(skc->sc_session_kb.kb_tfm);
794
795         memset(token->data, 0, token->len);
796         if (sk_fill_header(skc, &skh) != GSS_S_COMPLETE)
797                 return GSS_S_FAILURE;
798
799         skw.skw_header.data = token->data;
800         skw.skw_header.len = sizeof(skh);
801         memcpy(skw.skw_header.data, &skh, sizeof(skh));
802
803         sk_construct_rfc3686_iv(local_iv, skc->sc_host_random, skh.skh_iv);
804         skw.skw_cipher.data = skw.skw_header.data + skw.skw_header.len;
805         skw.skw_cipher.len = token->len - skw.skw_header.len - sht_bytes;
806         if (sk_encrypt_bulk(skc->sc_session_kb.kb_tfm, local_iv,
807                             desc, &skw.skw_cipher, adj_nob))
808                 return GSS_S_FAILURE;
809
810         skw.skw_hmac.data = skw.skw_cipher.data + skw.skw_cipher.len;
811         skw.skw_hmac.len = sht_bytes;
812         if (sk_make_hmac(skc->sc_hmac, &skc->sc_hmac_key, 1, &skw.skw_cipher,
813                          desc->bd_iov_count, GET_ENC_KIOV(desc), &skw.skw_hmac))
814                 return GSS_S_FAILURE;
815
816         return GSS_S_COMPLETE;
817 }
818
819 static
820 __u32 gss_unwrap_bulk_sk(struct gss_ctx *gss_context,
821                            struct ptlrpc_bulk_desc *desc,
822                            rawobj_t *token, int adj_nob)
823 {
824         struct sk_ctx *skc = gss_context->internal_ctx_id;
825         size_t sht_bytes = cfs_crypto_hash_digestsize(skc->sc_hmac);
826         struct sk_wire skw;
827         struct sk_hdr *skh;
828         __u8 local_iv[SK_IV_SIZE];
829         int rc;
830
831         LASSERT(skc->sc_session_kb.kb_tfm);
832
833         if (token->len < sizeof(skh) + sht_bytes)
834                 return GSS_S_DEFECTIVE_TOKEN;
835
836         skw.skw_header.data = token->data;
837         skw.skw_header.len = sizeof(struct sk_hdr);
838         skw.skw_cipher.data = skw.skw_header.data + skw.skw_header.len;
839         skw.skw_cipher.len = token->len - skw.skw_header.len - sht_bytes;
840         skw.skw_hmac.data = skw.skw_cipher.data + skw.skw_cipher.len;
841         skw.skw_hmac.len = sht_bytes;
842
843         skh = (struct sk_hdr *)skw.skw_header.data;
844         rc = sk_verify_header(skh);
845         if (rc != GSS_S_COMPLETE)
846                 return rc;
847
848         rc = sk_verify_bulk_hmac(skc->sc_hmac, &skc->sc_hmac_key, 1,
849                                  &skw.skw_cipher, desc->bd_iov_count,
850                                  GET_ENC_KIOV(desc), desc->bd_nob,
851                                  &skw.skw_hmac);
852         if (rc)
853                 return rc;
854
855         sk_construct_rfc3686_iv(local_iv, skc->sc_peer_random, skh->skh_iv);
856         rc = sk_decrypt_bulk(skc->sc_session_kb.kb_tfm, local_iv,
857                              desc, &skw.skw_cipher, adj_nob);
858         if (rc)
859                 return rc;
860
861         return GSS_S_COMPLETE;
862 }
863
864 static
865 void gss_delete_sec_context_sk(void *internal_context)
866 {
867         struct sk_ctx *sk_context = internal_context;
868         sk_delete_context(sk_context);
869 }
870
871 int gss_display_sk(struct gss_ctx *gss_context, char *buf, int bufsize)
872 {
873         return snprintf(buf, bufsize, "sk");
874 }
875
876 static struct gss_api_ops gss_sk_ops = {
877         .gss_import_sec_context     = gss_import_sec_context_sk,
878         .gss_copy_reverse_context   = gss_copy_reverse_context_sk,
879         .gss_inquire_context        = gss_inquire_context_sk,
880         .gss_get_mic                = gss_get_mic_sk,
881         .gss_verify_mic             = gss_verify_mic_sk,
882         .gss_wrap                   = gss_wrap_sk,
883         .gss_unwrap                 = gss_unwrap_sk,
884         .gss_prep_bulk              = gss_prep_bulk_sk,
885         .gss_wrap_bulk              = gss_wrap_bulk_sk,
886         .gss_unwrap_bulk            = gss_unwrap_bulk_sk,
887         .gss_delete_sec_context     = gss_delete_sec_context_sk,
888         .gss_display                = gss_display_sk,
889 };
890
891 static struct subflavor_desc gss_sk_sfs[] = {
892         {
893                 .sf_subflavor   = SPTLRPC_SUBFLVR_SKN,
894                 .sf_qop         = 0,
895                 .sf_service     = SPTLRPC_SVC_NULL,
896                 .sf_name        = "skn"
897         },
898         {
899                 .sf_subflavor   = SPTLRPC_SUBFLVR_SKA,
900                 .sf_qop         = 0,
901                 .sf_service     = SPTLRPC_SVC_AUTH,
902                 .sf_name        = "ska"
903         },
904         {
905                 .sf_subflavor   = SPTLRPC_SUBFLVR_SKI,
906                 .sf_qop         = 0,
907                 .sf_service     = SPTLRPC_SVC_INTG,
908                 .sf_name        = "ski"
909         },
910         {
911                 .sf_subflavor   = SPTLRPC_SUBFLVR_SKPI,
912                 .sf_qop         = 0,
913                 .sf_service     = SPTLRPC_SVC_PRIV,
914                 .sf_name        = "skpi"
915         },
916 };
917
918 static struct gss_api_mech gss_sk_mech = {
919         /* .gm_owner uses default NULL value for THIS_MODULE */
920         .gm_name        = "sk",
921         .gm_oid         = (rawobj_t) {
922                 .len = 12,
923                 .data = "\053\006\001\004\001\311\146\215\126\001\000\001",
924         },
925         .gm_ops         = &gss_sk_ops,
926         .gm_sf_num      = 4,
927         .gm_sfs         = gss_sk_sfs,
928 };
929
930 int __init init_sk_module(void)
931 {
932         int status;
933
934         status = lgss_mech_register(&gss_sk_mech);
935         if (status)
936                 CERROR("Failed to register sk gss mechanism!\n");
937
938         return status;
939 }
940
941 void cleanup_sk_module(void)
942 {
943         lgss_mech_unregister(&gss_sk_mech);
944 }