]> git.karo-electronics.de Git - karo-tx-linux.git/blob - net/rxrpc/rxkad.c
Merge remote-tracking branch 'regulator/for-next'
[karo-tx-linux.git] / net / rxrpc / rxkad.c
1 /* Kerberos-based RxRPC security
2  *
3  * Copyright (C) 2007 Red Hat, Inc. All Rights Reserved.
4  * Written by David Howells (dhowells@redhat.com)
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version
9  * 2 of the License, or (at your option) any later version.
10  */
11
12 #include <crypto/skcipher.h>
13 #include <linux/module.h>
14 #include <linux/net.h>
15 #include <linux/skbuff.h>
16 #include <linux/udp.h>
17 #include <linux/scatterlist.h>
18 #include <linux/ctype.h>
19 #include <linux/slab.h>
20 #include <net/sock.h>
21 #include <net/af_rxrpc.h>
22 #include <keys/rxrpc-type.h>
23 #define rxrpc_debug rxkad_debug
24 #include "ar-internal.h"
25
26 #define RXKAD_VERSION                   2
27 #define MAXKRB5TICKETLEN                1024
28 #define RXKAD_TKT_TYPE_KERBEROS_V5      256
29 #define ANAME_SZ                        40      /* size of authentication name */
30 #define INST_SZ                         40      /* size of principal's instance */
31 #define REALM_SZ                        40      /* size of principal's auth domain */
32 #define SNAME_SZ                        40      /* size of service name */
33
34 unsigned int rxrpc_debug;
35 module_param_named(debug, rxrpc_debug, uint, S_IWUSR | S_IRUGO);
36 MODULE_PARM_DESC(debug, "rxkad debugging mask");
37
38 struct rxkad_level1_hdr {
39         __be32  data_size;      /* true data size (excluding padding) */
40 };
41
42 struct rxkad_level2_hdr {
43         __be32  data_size;      /* true data size (excluding padding) */
44         __be32  checksum;       /* decrypted data checksum */
45 };
46
47 MODULE_DESCRIPTION("RxRPC network protocol type-2 security (Kerberos 4)");
48 MODULE_AUTHOR("Red Hat, Inc.");
49 MODULE_LICENSE("GPL");
50
51 /*
52  * this holds a pinned cipher so that keventd doesn't get called by the cipher
53  * alloc routine, but since we have it to hand, we use it to decrypt RESPONSE
54  * packets
55  */
56 static struct crypto_skcipher *rxkad_ci;
57 static DEFINE_MUTEX(rxkad_ci_mutex);
58
59 /*
60  * initialise connection security
61  */
62 static int rxkad_init_connection_security(struct rxrpc_connection *conn)
63 {
64         struct crypto_skcipher *ci;
65         struct rxrpc_key_token *token;
66         int ret;
67
68         _enter("{%d},{%x}", conn->debug_id, key_serial(conn->key));
69
70         token = conn->key->payload.data[0];
71         conn->security_ix = token->security_index;
72
73         ci = crypto_alloc_skcipher("pcbc(fcrypt)", 0, CRYPTO_ALG_ASYNC);
74         if (IS_ERR(ci)) {
75                 _debug("no cipher");
76                 ret = PTR_ERR(ci);
77                 goto error;
78         }
79
80         if (crypto_skcipher_setkey(ci, token->kad->session_key,
81                                    sizeof(token->kad->session_key)) < 0)
82                 BUG();
83
84         switch (conn->security_level) {
85         case RXRPC_SECURITY_PLAIN:
86                 break;
87         case RXRPC_SECURITY_AUTH:
88                 conn->size_align = 8;
89                 conn->security_size = sizeof(struct rxkad_level1_hdr);
90                 conn->header_size += sizeof(struct rxkad_level1_hdr);
91                 break;
92         case RXRPC_SECURITY_ENCRYPT:
93                 conn->size_align = 8;
94                 conn->security_size = sizeof(struct rxkad_level2_hdr);
95                 conn->header_size += sizeof(struct rxkad_level2_hdr);
96                 break;
97         default:
98                 ret = -EKEYREJECTED;
99                 goto error;
100         }
101
102         conn->cipher = ci;
103         ret = 0;
104 error:
105         _leave(" = %d", ret);
106         return ret;
107 }
108
109 /*
110  * prime the encryption state with the invariant parts of a connection's
111  * description
112  */
113 static void rxkad_prime_packet_security(struct rxrpc_connection *conn)
114 {
115         struct rxrpc_key_token *token;
116         SKCIPHER_REQUEST_ON_STACK(req, conn->cipher);
117         struct scatterlist sg[2];
118         struct rxrpc_crypt iv;
119         struct {
120                 __be32 x[4];
121         } tmpbuf __attribute__((aligned(16))); /* must all be in same page */
122
123         _enter("");
124
125         if (!conn->key)
126                 return;
127
128         token = conn->key->payload.data[0];
129         memcpy(&iv, token->kad->session_key, sizeof(iv));
130
131         tmpbuf.x[0] = conn->epoch;
132         tmpbuf.x[1] = conn->cid;
133         tmpbuf.x[2] = 0;
134         tmpbuf.x[3] = htonl(conn->security_ix);
135
136         sg_init_one(&sg[0], &tmpbuf, sizeof(tmpbuf));
137         sg_init_one(&sg[1], &tmpbuf, sizeof(tmpbuf));
138
139         skcipher_request_set_tfm(req, conn->cipher);
140         skcipher_request_set_callback(req, 0, NULL, NULL);
141         skcipher_request_set_crypt(req, &sg[1], &sg[0], sizeof(tmpbuf), iv.x);
142
143         crypto_skcipher_encrypt(req);
144         skcipher_request_zero(req);
145
146         memcpy(&conn->csum_iv, &tmpbuf.x[2], sizeof(conn->csum_iv));
147         ASSERTCMP(conn->csum_iv.n[0], ==, tmpbuf.x[2]);
148
149         _leave("");
150 }
151
152 /*
153  * partially encrypt a packet (level 1 security)
154  */
155 static int rxkad_secure_packet_auth(const struct rxrpc_call *call,
156                                     struct sk_buff *skb,
157                                     u32 data_size,
158                                     void *sechdr)
159 {
160         struct rxrpc_skb_priv *sp;
161         SKCIPHER_REQUEST_ON_STACK(req, call->conn->cipher);
162         struct rxrpc_crypt iv;
163         struct scatterlist sg[2];
164         struct {
165                 struct rxkad_level1_hdr hdr;
166                 __be32  first;  /* first four bytes of data and padding */
167         } tmpbuf __attribute__((aligned(8))); /* must all be in same page */
168         u16 check;
169
170         sp = rxrpc_skb(skb);
171
172         _enter("");
173
174         check = ntohl(sp->hdr.seq ^ sp->hdr.callNumber);
175         data_size |= (u32) check << 16;
176
177         tmpbuf.hdr.data_size = htonl(data_size);
178         memcpy(&tmpbuf.first, sechdr + 4, sizeof(tmpbuf.first));
179
180         /* start the encryption afresh */
181         memset(&iv, 0, sizeof(iv));
182
183         sg_init_one(&sg[0], &tmpbuf, sizeof(tmpbuf));
184         sg_init_one(&sg[1], &tmpbuf, sizeof(tmpbuf));
185
186         skcipher_request_set_tfm(req, call->conn->cipher);
187         skcipher_request_set_callback(req, 0, NULL, NULL);
188         skcipher_request_set_crypt(req, &sg[1], &sg[0], sizeof(tmpbuf), iv.x);
189
190         crypto_skcipher_encrypt(req);
191         skcipher_request_zero(req);
192
193         memcpy(sechdr, &tmpbuf, sizeof(tmpbuf));
194
195         _leave(" = 0");
196         return 0;
197 }
198
199 /*
200  * wholly encrypt a packet (level 2 security)
201  */
202 static int rxkad_secure_packet_encrypt(const struct rxrpc_call *call,
203                                         struct sk_buff *skb,
204                                         u32 data_size,
205                                         void *sechdr)
206 {
207         const struct rxrpc_key_token *token;
208         struct rxkad_level2_hdr rxkhdr
209                 __attribute__((aligned(8))); /* must be all on one page */
210         struct rxrpc_skb_priv *sp;
211         SKCIPHER_REQUEST_ON_STACK(req, call->conn->cipher);
212         struct rxrpc_crypt iv;
213         struct scatterlist sg[16];
214         struct sk_buff *trailer;
215         unsigned int len;
216         u16 check;
217         int nsg;
218         int err;
219
220         sp = rxrpc_skb(skb);
221
222         _enter("");
223
224         check = ntohl(sp->hdr.seq ^ sp->hdr.callNumber);
225
226         rxkhdr.data_size = htonl(data_size | (u32) check << 16);
227         rxkhdr.checksum = 0;
228
229         /* encrypt from the session key */
230         token = call->conn->key->payload.data[0];
231         memcpy(&iv, token->kad->session_key, sizeof(iv));
232
233         sg_init_one(&sg[0], sechdr, sizeof(rxkhdr));
234         sg_init_one(&sg[1], &rxkhdr, sizeof(rxkhdr));
235
236         skcipher_request_set_tfm(req, call->conn->cipher);
237         skcipher_request_set_callback(req, 0, NULL, NULL);
238         skcipher_request_set_crypt(req, &sg[1], &sg[0], sizeof(rxkhdr), iv.x);
239
240         crypto_skcipher_encrypt(req);
241
242         /* we want to encrypt the skbuff in-place */
243         nsg = skb_cow_data(skb, 0, &trailer);
244         err = -ENOMEM;
245         if (nsg < 0 || nsg > 16)
246                 goto out;
247
248         len = data_size + call->conn->size_align - 1;
249         len &= ~(call->conn->size_align - 1);
250
251         sg_init_table(sg, nsg);
252         skb_to_sgvec(skb, sg, 0, len);
253
254         skcipher_request_set_crypt(req, sg, sg, len, iv.x);
255
256         crypto_skcipher_encrypt(req);
257
258         _leave(" = 0");
259         err = 0;
260
261 out:
262         skcipher_request_zero(req);
263         return err;
264 }
265
266 /*
267  * checksum an RxRPC packet header
268  */
269 static int rxkad_secure_packet(const struct rxrpc_call *call,
270                                 struct sk_buff *skb,
271                                 size_t data_size,
272                                 void *sechdr)
273 {
274         struct rxrpc_skb_priv *sp;
275         SKCIPHER_REQUEST_ON_STACK(req, call->conn->cipher);
276         struct rxrpc_crypt iv;
277         struct scatterlist sg[2];
278         struct {
279                 __be32 x[2];
280         } tmpbuf __attribute__((aligned(8))); /* must all be in same page */
281         __be32 x;
282         u32 y;
283         int ret;
284
285         sp = rxrpc_skb(skb);
286
287         _enter("{%d{%x}},{#%u},%zu,",
288                call->debug_id, key_serial(call->conn->key), ntohl(sp->hdr.seq),
289                data_size);
290
291         if (!call->conn->cipher)
292                 return 0;
293
294         ret = key_validate(call->conn->key);
295         if (ret < 0)
296                 return ret;
297
298         /* continue encrypting from where we left off */
299         memcpy(&iv, call->conn->csum_iv.x, sizeof(iv));
300
301         /* calculate the security checksum */
302         x = htonl(call->channel << (32 - RXRPC_CIDSHIFT));
303         x |= sp->hdr.seq & cpu_to_be32(0x3fffffff);
304         tmpbuf.x[0] = sp->hdr.callNumber;
305         tmpbuf.x[1] = x;
306
307         sg_init_one(&sg[0], &tmpbuf, sizeof(tmpbuf));
308         sg_init_one(&sg[1], &tmpbuf, sizeof(tmpbuf));
309
310         skcipher_request_set_tfm(req, call->conn->cipher);
311         skcipher_request_set_callback(req, 0, NULL, NULL);
312         skcipher_request_set_crypt(req, &sg[1], &sg[0], sizeof(tmpbuf), iv.x);
313
314         crypto_skcipher_encrypt(req);
315         skcipher_request_zero(req);
316
317         y = ntohl(tmpbuf.x[1]);
318         y = (y >> 16) & 0xffff;
319         if (y == 0)
320                 y = 1; /* zero checksums are not permitted */
321         sp->hdr.cksum = htons(y);
322
323         switch (call->conn->security_level) {
324         case RXRPC_SECURITY_PLAIN:
325                 ret = 0;
326                 break;
327         case RXRPC_SECURITY_AUTH:
328                 ret = rxkad_secure_packet_auth(call, skb, data_size, sechdr);
329                 break;
330         case RXRPC_SECURITY_ENCRYPT:
331                 ret = rxkad_secure_packet_encrypt(call, skb, data_size,
332                                                   sechdr);
333                 break;
334         default:
335                 ret = -EPERM;
336                 break;
337         }
338
339         _leave(" = %d [set %hx]", ret, y);
340         return ret;
341 }
342
343 /*
344  * decrypt partial encryption on a packet (level 1 security)
345  */
346 static int rxkad_verify_packet_auth(const struct rxrpc_call *call,
347                                     struct sk_buff *skb,
348                                     u32 *_abort_code)
349 {
350         struct rxkad_level1_hdr sechdr;
351         struct rxrpc_skb_priv *sp;
352         SKCIPHER_REQUEST_ON_STACK(req, call->conn->cipher);
353         struct rxrpc_crypt iv;
354         struct scatterlist sg[16];
355         struct sk_buff *trailer;
356         u32 data_size, buf;
357         u16 check;
358         int nsg;
359
360         _enter("");
361
362         sp = rxrpc_skb(skb);
363
364         /* we want to decrypt the skbuff in-place */
365         nsg = skb_cow_data(skb, 0, &trailer);
366         if (nsg < 0 || nsg > 16)
367                 goto nomem;
368
369         sg_init_table(sg, nsg);
370         skb_to_sgvec(skb, sg, 0, 8);
371
372         /* start the decryption afresh */
373         memset(&iv, 0, sizeof(iv));
374
375         skcipher_request_set_tfm(req, call->conn->cipher);
376         skcipher_request_set_callback(req, 0, NULL, NULL);
377         skcipher_request_set_crypt(req, sg, sg, 8, iv.x);
378
379         crypto_skcipher_decrypt(req);
380         skcipher_request_zero(req);
381
382         /* remove the decrypted packet length */
383         if (skb_copy_bits(skb, 0, &sechdr, sizeof(sechdr)) < 0)
384                 goto datalen_error;
385         if (!skb_pull(skb, sizeof(sechdr)))
386                 BUG();
387
388         buf = ntohl(sechdr.data_size);
389         data_size = buf & 0xffff;
390
391         check = buf >> 16;
392         check ^= ntohl(sp->hdr.seq ^ sp->hdr.callNumber);
393         check &= 0xffff;
394         if (check != 0) {
395                 *_abort_code = RXKADSEALEDINCON;
396                 goto protocol_error;
397         }
398
399         /* shorten the packet to remove the padding */
400         if (data_size > skb->len)
401                 goto datalen_error;
402         else if (data_size < skb->len)
403                 skb->len = data_size;
404
405         _leave(" = 0 [dlen=%x]", data_size);
406         return 0;
407
408 datalen_error:
409         *_abort_code = RXKADDATALEN;
410 protocol_error:
411         _leave(" = -EPROTO");
412         return -EPROTO;
413
414 nomem:
415         _leave(" = -ENOMEM");
416         return -ENOMEM;
417 }
418
419 /*
420  * wholly decrypt a packet (level 2 security)
421  */
422 static int rxkad_verify_packet_encrypt(const struct rxrpc_call *call,
423                                        struct sk_buff *skb,
424                                        u32 *_abort_code)
425 {
426         const struct rxrpc_key_token *token;
427         struct rxkad_level2_hdr sechdr;
428         struct rxrpc_skb_priv *sp;
429         SKCIPHER_REQUEST_ON_STACK(req, call->conn->cipher);
430         struct rxrpc_crypt iv;
431         struct scatterlist _sg[4], *sg;
432         struct sk_buff *trailer;
433         u32 data_size, buf;
434         u16 check;
435         int nsg;
436
437         _enter(",{%d}", skb->len);
438
439         sp = rxrpc_skb(skb);
440
441         /* we want to decrypt the skbuff in-place */
442         nsg = skb_cow_data(skb, 0, &trailer);
443         if (nsg < 0)
444                 goto nomem;
445
446         sg = _sg;
447         if (unlikely(nsg > 4)) {
448                 sg = kmalloc(sizeof(*sg) * nsg, GFP_NOIO);
449                 if (!sg)
450                         goto nomem;
451         }
452
453         sg_init_table(sg, nsg);
454         skb_to_sgvec(skb, sg, 0, skb->len);
455
456         /* decrypt from the session key */
457         token = call->conn->key->payload.data[0];
458         memcpy(&iv, token->kad->session_key, sizeof(iv));
459
460         skcipher_request_set_tfm(req, call->conn->cipher);
461         skcipher_request_set_callback(req, 0, NULL, NULL);
462         skcipher_request_set_crypt(req, sg, sg, skb->len, iv.x);
463
464         crypto_skcipher_decrypt(req);
465         skcipher_request_zero(req);
466         if (sg != _sg)
467                 kfree(sg);
468
469         /* remove the decrypted packet length */
470         if (skb_copy_bits(skb, 0, &sechdr, sizeof(sechdr)) < 0)
471                 goto datalen_error;
472         if (!skb_pull(skb, sizeof(sechdr)))
473                 BUG();
474
475         buf = ntohl(sechdr.data_size);
476         data_size = buf & 0xffff;
477
478         check = buf >> 16;
479         check ^= ntohl(sp->hdr.seq ^ sp->hdr.callNumber);
480         check &= 0xffff;
481         if (check != 0) {
482                 *_abort_code = RXKADSEALEDINCON;
483                 goto protocol_error;
484         }
485
486         /* shorten the packet to remove the padding */
487         if (data_size > skb->len)
488                 goto datalen_error;
489         else if (data_size < skb->len)
490                 skb->len = data_size;
491
492         _leave(" = 0 [dlen=%x]", data_size);
493         return 0;
494
495 datalen_error:
496         *_abort_code = RXKADDATALEN;
497 protocol_error:
498         _leave(" = -EPROTO");
499         return -EPROTO;
500
501 nomem:
502         _leave(" = -ENOMEM");
503         return -ENOMEM;
504 }
505
506 /*
507  * verify the security on a received packet
508  */
509 static int rxkad_verify_packet(const struct rxrpc_call *call,
510                                struct sk_buff *skb,
511                                u32 *_abort_code)
512 {
513         SKCIPHER_REQUEST_ON_STACK(req, call->conn->cipher);
514         struct rxrpc_skb_priv *sp;
515         struct rxrpc_crypt iv;
516         struct scatterlist sg[2];
517         struct {
518                 __be32 x[2];
519         } tmpbuf __attribute__((aligned(8))); /* must all be in same page */
520         __be32 x;
521         __be16 cksum;
522         u32 y;
523         int ret;
524
525         sp = rxrpc_skb(skb);
526
527         _enter("{%d{%x}},{#%u}",
528                call->debug_id, key_serial(call->conn->key),
529                ntohl(sp->hdr.seq));
530
531         if (!call->conn->cipher)
532                 return 0;
533
534         if (sp->hdr.securityIndex != RXRPC_SECURITY_RXKAD) {
535                 *_abort_code = RXKADINCONSISTENCY;
536                 _leave(" = -EPROTO [not rxkad]");
537                 return -EPROTO;
538         }
539
540         /* continue encrypting from where we left off */
541         memcpy(&iv, call->conn->csum_iv.x, sizeof(iv));
542
543         /* validate the security checksum */
544         x = htonl(call->channel << (32 - RXRPC_CIDSHIFT));
545         x |= sp->hdr.seq & cpu_to_be32(0x3fffffff);
546         tmpbuf.x[0] = call->call_id;
547         tmpbuf.x[1] = x;
548
549         sg_init_one(&sg[0], &tmpbuf, sizeof(tmpbuf));
550         sg_init_one(&sg[1], &tmpbuf, sizeof(tmpbuf));
551
552         skcipher_request_set_tfm(req, call->conn->cipher);
553         skcipher_request_set_callback(req, 0, NULL, NULL);
554         skcipher_request_set_crypt(req, &sg[1], &sg[0], sizeof(tmpbuf), iv.x);
555
556         crypto_skcipher_encrypt(req);
557         skcipher_request_zero(req);
558
559         y = ntohl(tmpbuf.x[1]);
560         y = (y >> 16) & 0xffff;
561         if (y == 0)
562                 y = 1; /* zero checksums are not permitted */
563
564         cksum = htons(y);
565         if (sp->hdr.cksum != cksum) {
566                 *_abort_code = RXKADSEALEDINCON;
567                 _leave(" = -EPROTO [csum failed]");
568                 return -EPROTO;
569         }
570
571         switch (call->conn->security_level) {
572         case RXRPC_SECURITY_PLAIN:
573                 ret = 0;
574                 break;
575         case RXRPC_SECURITY_AUTH:
576                 ret = rxkad_verify_packet_auth(call, skb, _abort_code);
577                 break;
578         case RXRPC_SECURITY_ENCRYPT:
579                 ret = rxkad_verify_packet_encrypt(call, skb, _abort_code);
580                 break;
581         default:
582                 ret = -ENOANO;
583                 break;
584         }
585
586         _leave(" = %d", ret);
587         return ret;
588 }
589
590 /*
591  * issue a challenge
592  */
593 static int rxkad_issue_challenge(struct rxrpc_connection *conn)
594 {
595         struct rxkad_challenge challenge;
596         struct rxrpc_header hdr;
597         struct msghdr msg;
598         struct kvec iov[2];
599         size_t len;
600         int ret;
601
602         _enter("{%d,%x}", conn->debug_id, key_serial(conn->key));
603
604         ret = key_validate(conn->key);
605         if (ret < 0)
606                 return ret;
607
608         get_random_bytes(&conn->security_nonce, sizeof(conn->security_nonce));
609
610         challenge.version       = htonl(2);
611         challenge.nonce         = htonl(conn->security_nonce);
612         challenge.min_level     = htonl(0);
613         challenge.__padding     = 0;
614
615         msg.msg_name    = &conn->trans->peer->srx.transport.sin;
616         msg.msg_namelen = sizeof(conn->trans->peer->srx.transport.sin);
617         msg.msg_control = NULL;
618         msg.msg_controllen = 0;
619         msg.msg_flags   = 0;
620
621         hdr.epoch       = conn->epoch;
622         hdr.cid         = conn->cid;
623         hdr.callNumber  = 0;
624         hdr.seq         = 0;
625         hdr.type        = RXRPC_PACKET_TYPE_CHALLENGE;
626         hdr.flags       = conn->out_clientflag;
627         hdr.userStatus  = 0;
628         hdr.securityIndex = conn->security_ix;
629         hdr._rsvd       = 0;
630         hdr.serviceId   = conn->service_id;
631
632         iov[0].iov_base = &hdr;
633         iov[0].iov_len  = sizeof(hdr);
634         iov[1].iov_base = &challenge;
635         iov[1].iov_len  = sizeof(challenge);
636
637         len = iov[0].iov_len + iov[1].iov_len;
638
639         hdr.serial = htonl(atomic_inc_return(&conn->serial));
640         _proto("Tx CHALLENGE %%%u", ntohl(hdr.serial));
641
642         ret = kernel_sendmsg(conn->trans->local->socket, &msg, iov, 2, len);
643         if (ret < 0) {
644                 _debug("sendmsg failed: %d", ret);
645                 return -EAGAIN;
646         }
647
648         _leave(" = 0");
649         return 0;
650 }
651
652 /*
653  * send a Kerberos security response
654  */
655 static int rxkad_send_response(struct rxrpc_connection *conn,
656                                struct rxrpc_header *hdr,
657                                struct rxkad_response *resp,
658                                const struct rxkad_key *s2)
659 {
660         struct msghdr msg;
661         struct kvec iov[3];
662         size_t len;
663         int ret;
664
665         _enter("");
666
667         msg.msg_name    = &conn->trans->peer->srx.transport.sin;
668         msg.msg_namelen = sizeof(conn->trans->peer->srx.transport.sin);
669         msg.msg_control = NULL;
670         msg.msg_controllen = 0;
671         msg.msg_flags   = 0;
672
673         hdr->epoch      = conn->epoch;
674         hdr->seq        = 0;
675         hdr->type       = RXRPC_PACKET_TYPE_RESPONSE;
676         hdr->flags      = conn->out_clientflag;
677         hdr->userStatus = 0;
678         hdr->_rsvd      = 0;
679
680         iov[0].iov_base = hdr;
681         iov[0].iov_len  = sizeof(*hdr);
682         iov[1].iov_base = resp;
683         iov[1].iov_len  = sizeof(*resp);
684         iov[2].iov_base = (void *) s2->ticket;
685         iov[2].iov_len  = s2->ticket_len;
686
687         len = iov[0].iov_len + iov[1].iov_len + iov[2].iov_len;
688
689         hdr->serial = htonl(atomic_inc_return(&conn->serial));
690         _proto("Tx RESPONSE %%%u", ntohl(hdr->serial));
691
692         ret = kernel_sendmsg(conn->trans->local->socket, &msg, iov, 3, len);
693         if (ret < 0) {
694                 _debug("sendmsg failed: %d", ret);
695                 return -EAGAIN;
696         }
697
698         _leave(" = 0");
699         return 0;
700 }
701
702 /*
703  * calculate the response checksum
704  */
705 static void rxkad_calc_response_checksum(struct rxkad_response *response)
706 {
707         u32 csum = 1000003;
708         int loop;
709         u8 *p = (u8 *) response;
710
711         for (loop = sizeof(*response); loop > 0; loop--)
712                 csum = csum * 0x10204081 + *p++;
713
714         response->encrypted.checksum = htonl(csum);
715 }
716
717 /*
718  * load a scatterlist with a potentially split-page buffer
719  */
720 static void rxkad_sg_set_buf2(struct scatterlist sg[2],
721                               void *buf, size_t buflen)
722 {
723         int nsg = 1;
724
725         sg_init_table(sg, 2);
726
727         sg_set_buf(&sg[0], buf, buflen);
728         if (sg[0].offset + buflen > PAGE_SIZE) {
729                 /* the buffer was split over two pages */
730                 sg[0].length = PAGE_SIZE - sg[0].offset;
731                 sg_set_buf(&sg[1], buf + sg[0].length, buflen - sg[0].length);
732                 nsg++;
733         }
734
735         sg_mark_end(&sg[nsg - 1]);
736
737         ASSERTCMP(sg[0].length + sg[1].length, ==, buflen);
738 }
739
740 /*
741  * encrypt the response packet
742  */
743 static void rxkad_encrypt_response(struct rxrpc_connection *conn,
744                                    struct rxkad_response *resp,
745                                    const struct rxkad_key *s2)
746 {
747         SKCIPHER_REQUEST_ON_STACK(req, conn->cipher);
748         struct rxrpc_crypt iv;
749         struct scatterlist sg[2];
750
751         /* continue encrypting from where we left off */
752         memcpy(&iv, s2->session_key, sizeof(iv));
753
754         rxkad_sg_set_buf2(sg, &resp->encrypted, sizeof(resp->encrypted));
755
756         skcipher_request_set_tfm(req, conn->cipher);
757         skcipher_request_set_callback(req, 0, NULL, NULL);
758         skcipher_request_set_crypt(req, sg, sg, sizeof(resp->encrypted), iv.x);
759
760         crypto_skcipher_encrypt(req);
761         skcipher_request_zero(req);
762 }
763
764 /*
765  * respond to a challenge packet
766  */
767 static int rxkad_respond_to_challenge(struct rxrpc_connection *conn,
768                                       struct sk_buff *skb,
769                                       u32 *_abort_code)
770 {
771         const struct rxrpc_key_token *token;
772         struct rxkad_challenge challenge;
773         struct rxkad_response resp
774                 __attribute__((aligned(8))); /* must be aligned for crypto */
775         struct rxrpc_skb_priv *sp;
776         u32 version, nonce, min_level, abort_code;
777         int ret;
778
779         _enter("{%d,%x}", conn->debug_id, key_serial(conn->key));
780
781         if (!conn->key) {
782                 _leave(" = -EPROTO [no key]");
783                 return -EPROTO;
784         }
785
786         ret = key_validate(conn->key);
787         if (ret < 0) {
788                 *_abort_code = RXKADEXPIRED;
789                 return ret;
790         }
791
792         abort_code = RXKADPACKETSHORT;
793         sp = rxrpc_skb(skb);
794         if (skb_copy_bits(skb, 0, &challenge, sizeof(challenge)) < 0)
795                 goto protocol_error;
796
797         version = ntohl(challenge.version);
798         nonce = ntohl(challenge.nonce);
799         min_level = ntohl(challenge.min_level);
800
801         _proto("Rx CHALLENGE %%%u { v=%u n=%u ml=%u }",
802                ntohl(sp->hdr.serial), version, nonce, min_level);
803
804         abort_code = RXKADINCONSISTENCY;
805         if (version != RXKAD_VERSION)
806                 goto protocol_error;
807
808         abort_code = RXKADLEVELFAIL;
809         if (conn->security_level < min_level)
810                 goto protocol_error;
811
812         token = conn->key->payload.data[0];
813
814         /* build the response packet */
815         memset(&resp, 0, sizeof(resp));
816
817         resp.version = RXKAD_VERSION;
818         resp.encrypted.epoch = conn->epoch;
819         resp.encrypted.cid = conn->cid;
820         resp.encrypted.securityIndex = htonl(conn->security_ix);
821         resp.encrypted.call_id[0] =
822                 (conn->channels[0] ? conn->channels[0]->call_id : 0);
823         resp.encrypted.call_id[1] =
824                 (conn->channels[1] ? conn->channels[1]->call_id : 0);
825         resp.encrypted.call_id[2] =
826                 (conn->channels[2] ? conn->channels[2]->call_id : 0);
827         resp.encrypted.call_id[3] =
828                 (conn->channels[3] ? conn->channels[3]->call_id : 0);
829         resp.encrypted.inc_nonce = htonl(nonce + 1);
830         resp.encrypted.level = htonl(conn->security_level);
831         resp.kvno = htonl(token->kad->kvno);
832         resp.ticket_len = htonl(token->kad->ticket_len);
833
834         /* calculate the response checksum and then do the encryption */
835         rxkad_calc_response_checksum(&resp);
836         rxkad_encrypt_response(conn, &resp, token->kad);
837         return rxkad_send_response(conn, &sp->hdr, &resp, token->kad);
838
839 protocol_error:
840         *_abort_code = abort_code;
841         _leave(" = -EPROTO [%d]", abort_code);
842         return -EPROTO;
843 }
844
845 /*
846  * decrypt the kerberos IV ticket in the response
847  */
848 static int rxkad_decrypt_ticket(struct rxrpc_connection *conn,
849                                 void *ticket, size_t ticket_len,
850                                 struct rxrpc_crypt *_session_key,
851                                 time_t *_expiry,
852                                 u32 *_abort_code)
853 {
854         struct skcipher_request *req;
855         struct rxrpc_crypt iv, key;
856         struct scatterlist sg[1];
857         struct in_addr addr;
858         unsigned int life;
859         time_t issue, now;
860         bool little_endian;
861         int ret;
862         u8 *p, *q, *name, *end;
863
864         _enter("{%d},{%x}", conn->debug_id, key_serial(conn->server_key));
865
866         *_expiry = 0;
867
868         ret = key_validate(conn->server_key);
869         if (ret < 0) {
870                 switch (ret) {
871                 case -EKEYEXPIRED:
872                         *_abort_code = RXKADEXPIRED;
873                         goto error;
874                 default:
875                         *_abort_code = RXKADNOAUTH;
876                         goto error;
877                 }
878         }
879
880         ASSERT(conn->server_key->payload.data[0] != NULL);
881         ASSERTCMP((unsigned long) ticket & 7UL, ==, 0);
882
883         memcpy(&iv, &conn->server_key->payload.data[2], sizeof(iv));
884
885         req = skcipher_request_alloc(conn->server_key->payload.data[0],
886                                      GFP_NOFS);
887         if (!req) {
888                 *_abort_code = RXKADNOAUTH;
889                 ret = -ENOMEM;
890                 goto error;
891         }
892
893         sg_init_one(&sg[0], ticket, ticket_len);
894
895         skcipher_request_set_callback(req, 0, NULL, NULL);
896         skcipher_request_set_crypt(req, sg, sg, ticket_len, iv.x);
897
898         crypto_skcipher_decrypt(req);
899         skcipher_request_free(req);
900
901         p = ticket;
902         end = p + ticket_len;
903
904 #define Z(size)                                         \
905         ({                                              \
906                 u8 *__str = p;                          \
907                 q = memchr(p, 0, end - p);              \
908                 if (!q || q - p > (size))               \
909                         goto bad_ticket;                \
910                 for (; p < q; p++)                      \
911                         if (!isprint(*p))               \
912                                 goto bad_ticket;        \
913                 p++;                                    \
914                 __str;                                  \
915         })
916
917         /* extract the ticket flags */
918         _debug("KIV FLAGS: %x", *p);
919         little_endian = *p & 1;
920         p++;
921
922         /* extract the authentication name */
923         name = Z(ANAME_SZ);
924         _debug("KIV ANAME: %s", name);
925
926         /* extract the principal's instance */
927         name = Z(INST_SZ);
928         _debug("KIV INST : %s", name);
929
930         /* extract the principal's authentication domain */
931         name = Z(REALM_SZ);
932         _debug("KIV REALM: %s", name);
933
934         if (end - p < 4 + 8 + 4 + 2)
935                 goto bad_ticket;
936
937         /* get the IPv4 address of the entity that requested the ticket */
938         memcpy(&addr, p, sizeof(addr));
939         p += 4;
940         _debug("KIV ADDR : %pI4", &addr);
941
942         /* get the session key from the ticket */
943         memcpy(&key, p, sizeof(key));
944         p += 8;
945         _debug("KIV KEY  : %08x %08x", ntohl(key.n[0]), ntohl(key.n[1]));
946         memcpy(_session_key, &key, sizeof(key));
947
948         /* get the ticket's lifetime */
949         life = *p++ * 5 * 60;
950         _debug("KIV LIFE : %u", life);
951
952         /* get the issue time of the ticket */
953         if (little_endian) {
954                 __le32 stamp;
955                 memcpy(&stamp, p, 4);
956                 issue = le32_to_cpu(stamp);
957         } else {
958                 __be32 stamp;
959                 memcpy(&stamp, p, 4);
960                 issue = be32_to_cpu(stamp);
961         }
962         p += 4;
963         now = get_seconds();
964         _debug("KIV ISSUE: %lx [%lx]", issue, now);
965
966         /* check the ticket is in date */
967         if (issue > now) {
968                 *_abort_code = RXKADNOAUTH;
969                 ret = -EKEYREJECTED;
970                 goto error;
971         }
972
973         if (issue < now - life) {
974                 *_abort_code = RXKADEXPIRED;
975                 ret = -EKEYEXPIRED;
976                 goto error;
977         }
978
979         *_expiry = issue + life;
980
981         /* get the service name */
982         name = Z(SNAME_SZ);
983         _debug("KIV SNAME: %s", name);
984
985         /* get the service instance name */
986         name = Z(INST_SZ);
987         _debug("KIV SINST: %s", name);
988
989         ret = 0;
990 error:
991         _leave(" = %d", ret);
992         return ret;
993
994 bad_ticket:
995         *_abort_code = RXKADBADTICKET;
996         ret = -EBADMSG;
997         goto error;
998 }
999
1000 /*
1001  * decrypt the response packet
1002  */
1003 static void rxkad_decrypt_response(struct rxrpc_connection *conn,
1004                                    struct rxkad_response *resp,
1005                                    const struct rxrpc_crypt *session_key)
1006 {
1007         SKCIPHER_REQUEST_ON_STACK(req, rxkad_ci);
1008         struct scatterlist sg[2];
1009         struct rxrpc_crypt iv;
1010
1011         _enter(",,%08x%08x",
1012                ntohl(session_key->n[0]), ntohl(session_key->n[1]));
1013
1014         ASSERT(rxkad_ci != NULL);
1015
1016         mutex_lock(&rxkad_ci_mutex);
1017         if (crypto_skcipher_setkey(rxkad_ci, session_key->x,
1018                                    sizeof(*session_key)) < 0)
1019                 BUG();
1020
1021         memcpy(&iv, session_key, sizeof(iv));
1022
1023         rxkad_sg_set_buf2(sg, &resp->encrypted, sizeof(resp->encrypted));
1024
1025         skcipher_request_set_tfm(req, rxkad_ci);
1026         skcipher_request_set_callback(req, 0, NULL, NULL);
1027         skcipher_request_set_crypt(req, sg, sg, sizeof(resp->encrypted), iv.x);
1028
1029         crypto_skcipher_decrypt(req);
1030         skcipher_request_zero(req);
1031
1032         mutex_unlock(&rxkad_ci_mutex);
1033
1034         _leave("");
1035 }
1036
1037 /*
1038  * verify a response
1039  */
1040 static int rxkad_verify_response(struct rxrpc_connection *conn,
1041                                  struct sk_buff *skb,
1042                                  u32 *_abort_code)
1043 {
1044         struct rxkad_response response
1045                 __attribute__((aligned(8))); /* must be aligned for crypto */
1046         struct rxrpc_skb_priv *sp;
1047         struct rxrpc_crypt session_key;
1048         time_t expiry;
1049         void *ticket;
1050         u32 abort_code, version, kvno, ticket_len, level;
1051         __be32 csum;
1052         int ret;
1053
1054         _enter("{%d,%x}", conn->debug_id, key_serial(conn->server_key));
1055
1056         abort_code = RXKADPACKETSHORT;
1057         if (skb_copy_bits(skb, 0, &response, sizeof(response)) < 0)
1058                 goto protocol_error;
1059         if (!pskb_pull(skb, sizeof(response)))
1060                 BUG();
1061
1062         version = ntohl(response.version);
1063         ticket_len = ntohl(response.ticket_len);
1064         kvno = ntohl(response.kvno);
1065         sp = rxrpc_skb(skb);
1066         _proto("Rx RESPONSE %%%u { v=%u kv=%u tl=%u }",
1067                ntohl(sp->hdr.serial), version, kvno, ticket_len);
1068
1069         abort_code = RXKADINCONSISTENCY;
1070         if (version != RXKAD_VERSION)
1071                 goto protocol_error;
1072
1073         abort_code = RXKADTICKETLEN;
1074         if (ticket_len < 4 || ticket_len > MAXKRB5TICKETLEN)
1075                 goto protocol_error;
1076
1077         abort_code = RXKADUNKNOWNKEY;
1078         if (kvno >= RXKAD_TKT_TYPE_KERBEROS_V5)
1079                 goto protocol_error;
1080
1081         /* extract the kerberos ticket and decrypt and decode it */
1082         ticket = kmalloc(ticket_len, GFP_NOFS);
1083         if (!ticket)
1084                 return -ENOMEM;
1085
1086         abort_code = RXKADPACKETSHORT;
1087         if (skb_copy_bits(skb, 0, ticket, ticket_len) < 0)
1088                 goto protocol_error_free;
1089
1090         ret = rxkad_decrypt_ticket(conn, ticket, ticket_len, &session_key,
1091                                    &expiry, &abort_code);
1092         if (ret < 0) {
1093                 *_abort_code = abort_code;
1094                 kfree(ticket);
1095                 return ret;
1096         }
1097
1098         /* use the session key from inside the ticket to decrypt the
1099          * response */
1100         rxkad_decrypt_response(conn, &response, &session_key);
1101
1102         abort_code = RXKADSEALEDINCON;
1103         if (response.encrypted.epoch != conn->epoch)
1104                 goto protocol_error_free;
1105         if (response.encrypted.cid != conn->cid)
1106                 goto protocol_error_free;
1107         if (ntohl(response.encrypted.securityIndex) != conn->security_ix)
1108                 goto protocol_error_free;
1109         csum = response.encrypted.checksum;
1110         response.encrypted.checksum = 0;
1111         rxkad_calc_response_checksum(&response);
1112         if (response.encrypted.checksum != csum)
1113                 goto protocol_error_free;
1114
1115         if (ntohl(response.encrypted.call_id[0]) > INT_MAX ||
1116             ntohl(response.encrypted.call_id[1]) > INT_MAX ||
1117             ntohl(response.encrypted.call_id[2]) > INT_MAX ||
1118             ntohl(response.encrypted.call_id[3]) > INT_MAX)
1119                 goto protocol_error_free;
1120
1121         abort_code = RXKADOUTOFSEQUENCE;
1122         if (response.encrypted.inc_nonce != htonl(conn->security_nonce + 1))
1123                 goto protocol_error_free;
1124
1125         abort_code = RXKADLEVELFAIL;
1126         level = ntohl(response.encrypted.level);
1127         if (level > RXRPC_SECURITY_ENCRYPT)
1128                 goto protocol_error_free;
1129         conn->security_level = level;
1130
1131         /* create a key to hold the security data and expiration time - after
1132          * this the connection security can be handled in exactly the same way
1133          * as for a client connection */
1134         ret = rxrpc_get_server_data_key(conn, &session_key, expiry, kvno);
1135         if (ret < 0) {
1136                 kfree(ticket);
1137                 return ret;
1138         }
1139
1140         kfree(ticket);
1141         _leave(" = 0");
1142         return 0;
1143
1144 protocol_error_free:
1145         kfree(ticket);
1146 protocol_error:
1147         *_abort_code = abort_code;
1148         _leave(" = -EPROTO [%d]", abort_code);
1149         return -EPROTO;
1150 }
1151
1152 /*
1153  * clear the connection security
1154  */
1155 static void rxkad_clear(struct rxrpc_connection *conn)
1156 {
1157         _enter("");
1158
1159         if (conn->cipher)
1160                 crypto_free_skcipher(conn->cipher);
1161 }
1162
1163 /*
1164  * RxRPC Kerberos-based security
1165  */
1166 static struct rxrpc_security rxkad = {
1167         .owner                          = THIS_MODULE,
1168         .name                           = "rxkad",
1169         .security_index                 = RXRPC_SECURITY_RXKAD,
1170         .init_connection_security       = rxkad_init_connection_security,
1171         .prime_packet_security          = rxkad_prime_packet_security,
1172         .secure_packet                  = rxkad_secure_packet,
1173         .verify_packet                  = rxkad_verify_packet,
1174         .issue_challenge                = rxkad_issue_challenge,
1175         .respond_to_challenge           = rxkad_respond_to_challenge,
1176         .verify_response                = rxkad_verify_response,
1177         .clear                          = rxkad_clear,
1178 };
1179
1180 static __init int rxkad_init(void)
1181 {
1182         _enter("");
1183
1184         /* pin the cipher we need so that the crypto layer doesn't invoke
1185          * keventd to go get it */
1186         rxkad_ci = crypto_alloc_skcipher("pcbc(fcrypt)", 0, CRYPTO_ALG_ASYNC);
1187         if (IS_ERR(rxkad_ci))
1188                 return PTR_ERR(rxkad_ci);
1189
1190         return rxrpc_register_security(&rxkad);
1191 }
1192
1193 module_init(rxkad_init);
1194
1195 static __exit void rxkad_exit(void)
1196 {
1197         _enter("");
1198
1199         rxrpc_unregister_security(&rxkad);
1200         crypto_free_skcipher(rxkad_ci);
1201 }
1202
1203 module_exit(rxkad_exit);