netfilter: nf_tables: add register parsing/dumping helpers
[firefly-linux-kernel-4.4.55.git] / net / core / filter.c
1 /*
2  * Linux Socket Filter - Kernel level socket filtering
3  *
4  * Based on the design of the Berkeley Packet Filter. The new
5  * internal format has been designed by PLUMgrid:
6  *
7  *      Copyright (c) 2011 - 2014 PLUMgrid, http://plumgrid.com
8  *
9  * Authors:
10  *
11  *      Jay Schulist <jschlst@samba.org>
12  *      Alexei Starovoitov <ast@plumgrid.com>
13  *      Daniel Borkmann <dborkman@redhat.com>
14  *
15  * This program is free software; you can redistribute it and/or
16  * modify it under the terms of the GNU General Public License
17  * as published by the Free Software Foundation; either version
18  * 2 of the License, or (at your option) any later version.
19  *
20  * Andi Kleen - Fix a few bad bugs and races.
21  * Kris Katterjohn - Added many additional checks in bpf_check_classic()
22  */
23
24 #include <linux/module.h>
25 #include <linux/types.h>
26 #include <linux/mm.h>
27 #include <linux/fcntl.h>
28 #include <linux/socket.h>
29 #include <linux/in.h>
30 #include <linux/inet.h>
31 #include <linux/netdevice.h>
32 #include <linux/if_packet.h>
33 #include <linux/gfp.h>
34 #include <net/ip.h>
35 #include <net/protocol.h>
36 #include <net/netlink.h>
37 #include <linux/skbuff.h>
38 #include <net/sock.h>
39 #include <linux/errno.h>
40 #include <linux/timer.h>
41 #include <asm/uaccess.h>
42 #include <asm/unaligned.h>
43 #include <linux/filter.h>
44 #include <linux/ratelimit.h>
45 #include <linux/seccomp.h>
46 #include <linux/if_vlan.h>
47 #include <linux/bpf.h>
48
49 /**
50  *      sk_filter - run a packet through a socket filter
51  *      @sk: sock associated with &sk_buff
52  *      @skb: buffer to filter
53  *
54  * Run the filter code and then cut skb->data to correct size returned by
55  * SK_RUN_FILTER. If pkt_len is 0 we toss packet. If skb->len is smaller
56  * than pkt_len we keep whole skb->data. This is the socket level
57  * wrapper to SK_RUN_FILTER. It returns 0 if the packet should
58  * be accepted or -EPERM if the packet should be tossed.
59  *
60  */
61 int sk_filter(struct sock *sk, struct sk_buff *skb)
62 {
63         int err;
64         struct sk_filter *filter;
65
66         /*
67          * If the skb was allocated from pfmemalloc reserves, only
68          * allow SOCK_MEMALLOC sockets to use it as this socket is
69          * helping free memory
70          */
71         if (skb_pfmemalloc(skb) && !sock_flag(sk, SOCK_MEMALLOC))
72                 return -ENOMEM;
73
74         err = security_sock_rcv_skb(sk, skb);
75         if (err)
76                 return err;
77
78         rcu_read_lock();
79         filter = rcu_dereference(sk->sk_filter);
80         if (filter) {
81                 unsigned int pkt_len = SK_RUN_FILTER(filter, skb);
82
83                 err = pkt_len ? pskb_trim(skb, pkt_len) : -EPERM;
84         }
85         rcu_read_unlock();
86
87         return err;
88 }
89 EXPORT_SYMBOL(sk_filter);
90
91 static u64 __skb_get_pay_offset(u64 ctx, u64 a, u64 x, u64 r4, u64 r5)
92 {
93         return skb_get_poff((struct sk_buff *)(unsigned long) ctx);
94 }
95
96 static u64 __skb_get_nlattr(u64 ctx, u64 a, u64 x, u64 r4, u64 r5)
97 {
98         struct sk_buff *skb = (struct sk_buff *)(unsigned long) ctx;
99         struct nlattr *nla;
100
101         if (skb_is_nonlinear(skb))
102                 return 0;
103
104         if (skb->len < sizeof(struct nlattr))
105                 return 0;
106
107         if (a > skb->len - sizeof(struct nlattr))
108                 return 0;
109
110         nla = nla_find((struct nlattr *) &skb->data[a], skb->len - a, x);
111         if (nla)
112                 return (void *) nla - (void *) skb->data;
113
114         return 0;
115 }
116
117 static u64 __skb_get_nlattr_nest(u64 ctx, u64 a, u64 x, u64 r4, u64 r5)
118 {
119         struct sk_buff *skb = (struct sk_buff *)(unsigned long) ctx;
120         struct nlattr *nla;
121
122         if (skb_is_nonlinear(skb))
123                 return 0;
124
125         if (skb->len < sizeof(struct nlattr))
126                 return 0;
127
128         if (a > skb->len - sizeof(struct nlattr))
129                 return 0;
130
131         nla = (struct nlattr *) &skb->data[a];
132         if (nla->nla_len > skb->len - a)
133                 return 0;
134
135         nla = nla_find_nested(nla, x);
136         if (nla)
137                 return (void *) nla - (void *) skb->data;
138
139         return 0;
140 }
141
142 static u64 __get_raw_cpu_id(u64 ctx, u64 a, u64 x, u64 r4, u64 r5)
143 {
144         return raw_smp_processor_id();
145 }
146
147 /* note that this only generates 32-bit random numbers */
148 static u64 __get_random_u32(u64 ctx, u64 a, u64 x, u64 r4, u64 r5)
149 {
150         return prandom_u32();
151 }
152
153 static u32 convert_skb_access(int skb_field, int dst_reg, int src_reg,
154                               struct bpf_insn *insn_buf)
155 {
156         struct bpf_insn *insn = insn_buf;
157
158         switch (skb_field) {
159         case SKF_AD_MARK:
160                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, mark) != 4);
161
162                 *insn++ = BPF_LDX_MEM(BPF_W, dst_reg, src_reg,
163                                       offsetof(struct sk_buff, mark));
164                 break;
165
166         case SKF_AD_PKTTYPE:
167                 *insn++ = BPF_LDX_MEM(BPF_B, dst_reg, src_reg, PKT_TYPE_OFFSET());
168                 *insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg, PKT_TYPE_MAX);
169 #ifdef __BIG_ENDIAN_BITFIELD
170                 *insn++ = BPF_ALU32_IMM(BPF_RSH, dst_reg, 5);
171 #endif
172                 break;
173
174         case SKF_AD_QUEUE:
175                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, queue_mapping) != 2);
176
177                 *insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
178                                       offsetof(struct sk_buff, queue_mapping));
179                 break;
180
181         case SKF_AD_VLAN_TAG:
182         case SKF_AD_VLAN_TAG_PRESENT:
183                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, vlan_tci) != 2);
184                 BUILD_BUG_ON(VLAN_TAG_PRESENT != 0x1000);
185
186                 /* dst_reg = *(u16 *) (src_reg + offsetof(vlan_tci)) */
187                 *insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
188                                       offsetof(struct sk_buff, vlan_tci));
189                 if (skb_field == SKF_AD_VLAN_TAG) {
190                         *insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg,
191                                                 ~VLAN_TAG_PRESENT);
192                 } else {
193                         /* dst_reg >>= 12 */
194                         *insn++ = BPF_ALU32_IMM(BPF_RSH, dst_reg, 12);
195                         /* dst_reg &= 1 */
196                         *insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg, 1);
197                 }
198                 break;
199         }
200
201         return insn - insn_buf;
202 }
203
204 static bool convert_bpf_extensions(struct sock_filter *fp,
205                                    struct bpf_insn **insnp)
206 {
207         struct bpf_insn *insn = *insnp;
208         u32 cnt;
209
210         switch (fp->k) {
211         case SKF_AD_OFF + SKF_AD_PROTOCOL:
212                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, protocol) != 2);
213
214                 /* A = *(u16 *) (CTX + offsetof(protocol)) */
215                 *insn++ = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_CTX,
216                                       offsetof(struct sk_buff, protocol));
217                 /* A = ntohs(A) [emitting a nop or swap16] */
218                 *insn = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, 16);
219                 break;
220
221         case SKF_AD_OFF + SKF_AD_PKTTYPE:
222                 cnt = convert_skb_access(SKF_AD_PKTTYPE, BPF_REG_A, BPF_REG_CTX, insn);
223                 insn += cnt - 1;
224                 break;
225
226         case SKF_AD_OFF + SKF_AD_IFINDEX:
227         case SKF_AD_OFF + SKF_AD_HATYPE:
228                 BUILD_BUG_ON(FIELD_SIZEOF(struct net_device, ifindex) != 4);
229                 BUILD_BUG_ON(FIELD_SIZEOF(struct net_device, type) != 2);
230                 BUILD_BUG_ON(bytes_to_bpf_size(FIELD_SIZEOF(struct sk_buff, dev)) < 0);
231
232                 *insn++ = BPF_LDX_MEM(bytes_to_bpf_size(FIELD_SIZEOF(struct sk_buff, dev)),
233                                       BPF_REG_TMP, BPF_REG_CTX,
234                                       offsetof(struct sk_buff, dev));
235                 /* if (tmp != 0) goto pc + 1 */
236                 *insn++ = BPF_JMP_IMM(BPF_JNE, BPF_REG_TMP, 0, 1);
237                 *insn++ = BPF_EXIT_INSN();
238                 if (fp->k == SKF_AD_OFF + SKF_AD_IFINDEX)
239                         *insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_TMP,
240                                             offsetof(struct net_device, ifindex));
241                 else
242                         *insn = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_TMP,
243                                             offsetof(struct net_device, type));
244                 break;
245
246         case SKF_AD_OFF + SKF_AD_MARK:
247                 cnt = convert_skb_access(SKF_AD_MARK, BPF_REG_A, BPF_REG_CTX, insn);
248                 insn += cnt - 1;
249                 break;
250
251         case SKF_AD_OFF + SKF_AD_RXHASH:
252                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, hash) != 4);
253
254                 *insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX,
255                                     offsetof(struct sk_buff, hash));
256                 break;
257
258         case SKF_AD_OFF + SKF_AD_QUEUE:
259                 cnt = convert_skb_access(SKF_AD_QUEUE, BPF_REG_A, BPF_REG_CTX, insn);
260                 insn += cnt - 1;
261                 break;
262
263         case SKF_AD_OFF + SKF_AD_VLAN_TAG:
264                 cnt = convert_skb_access(SKF_AD_VLAN_TAG,
265                                          BPF_REG_A, BPF_REG_CTX, insn);
266                 insn += cnt - 1;
267                 break;
268
269         case SKF_AD_OFF + SKF_AD_VLAN_TAG_PRESENT:
270                 cnt = convert_skb_access(SKF_AD_VLAN_TAG_PRESENT,
271                                          BPF_REG_A, BPF_REG_CTX, insn);
272                 insn += cnt - 1;
273                 break;
274
275         case SKF_AD_OFF + SKF_AD_VLAN_TPID:
276                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, vlan_proto) != 2);
277
278                 /* A = *(u16 *) (CTX + offsetof(vlan_proto)) */
279                 *insn++ = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_CTX,
280                                       offsetof(struct sk_buff, vlan_proto));
281                 /* A = ntohs(A) [emitting a nop or swap16] */
282                 *insn = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, 16);
283                 break;
284
285         case SKF_AD_OFF + SKF_AD_PAY_OFFSET:
286         case SKF_AD_OFF + SKF_AD_NLATTR:
287         case SKF_AD_OFF + SKF_AD_NLATTR_NEST:
288         case SKF_AD_OFF + SKF_AD_CPU:
289         case SKF_AD_OFF + SKF_AD_RANDOM:
290                 /* arg1 = CTX */
291                 *insn++ = BPF_MOV64_REG(BPF_REG_ARG1, BPF_REG_CTX);
292                 /* arg2 = A */
293                 *insn++ = BPF_MOV64_REG(BPF_REG_ARG2, BPF_REG_A);
294                 /* arg3 = X */
295                 *insn++ = BPF_MOV64_REG(BPF_REG_ARG3, BPF_REG_X);
296                 /* Emit call(arg1=CTX, arg2=A, arg3=X) */
297                 switch (fp->k) {
298                 case SKF_AD_OFF + SKF_AD_PAY_OFFSET:
299                         *insn = BPF_EMIT_CALL(__skb_get_pay_offset);
300                         break;
301                 case SKF_AD_OFF + SKF_AD_NLATTR:
302                         *insn = BPF_EMIT_CALL(__skb_get_nlattr);
303                         break;
304                 case SKF_AD_OFF + SKF_AD_NLATTR_NEST:
305                         *insn = BPF_EMIT_CALL(__skb_get_nlattr_nest);
306                         break;
307                 case SKF_AD_OFF + SKF_AD_CPU:
308                         *insn = BPF_EMIT_CALL(__get_raw_cpu_id);
309                         break;
310                 case SKF_AD_OFF + SKF_AD_RANDOM:
311                         *insn = BPF_EMIT_CALL(__get_random_u32);
312                         break;
313                 }
314                 break;
315
316         case SKF_AD_OFF + SKF_AD_ALU_XOR_X:
317                 /* A ^= X */
318                 *insn = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_X);
319                 break;
320
321         default:
322                 /* This is just a dummy call to avoid letting the compiler
323                  * evict __bpf_call_base() as an optimization. Placed here
324                  * where no-one bothers.
325                  */
326                 BUG_ON(__bpf_call_base(0, 0, 0, 0, 0) != 0);
327                 return false;
328         }
329
330         *insnp = insn;
331         return true;
332 }
333
334 /**
335  *      bpf_convert_filter - convert filter program
336  *      @prog: the user passed filter program
337  *      @len: the length of the user passed filter program
338  *      @new_prog: buffer where converted program will be stored
339  *      @new_len: pointer to store length of converted program
340  *
341  * Remap 'sock_filter' style BPF instruction set to 'sock_filter_ext' style.
342  * Conversion workflow:
343  *
344  * 1) First pass for calculating the new program length:
345  *   bpf_convert_filter(old_prog, old_len, NULL, &new_len)
346  *
347  * 2) 2nd pass to remap in two passes: 1st pass finds new
348  *    jump offsets, 2nd pass remapping:
349  *   new_prog = kmalloc(sizeof(struct bpf_insn) * new_len);
350  *   bpf_convert_filter(old_prog, old_len, new_prog, &new_len);
351  *
352  * User BPF's register A is mapped to our BPF register 6, user BPF
353  * register X is mapped to BPF register 7; frame pointer is always
354  * register 10; Context 'void *ctx' is stored in register 1, that is,
355  * for socket filters: ctx == 'struct sk_buff *', for seccomp:
356  * ctx == 'struct seccomp_data *'.
357  */
358 int bpf_convert_filter(struct sock_filter *prog, int len,
359                        struct bpf_insn *new_prog, int *new_len)
360 {
361         int new_flen = 0, pass = 0, target, i;
362         struct bpf_insn *new_insn;
363         struct sock_filter *fp;
364         int *addrs = NULL;
365         u8 bpf_src;
366
367         BUILD_BUG_ON(BPF_MEMWORDS * sizeof(u32) > MAX_BPF_STACK);
368         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
369
370         if (len <= 0 || len > BPF_MAXINSNS)
371                 return -EINVAL;
372
373         if (new_prog) {
374                 addrs = kcalloc(len, sizeof(*addrs), GFP_KERNEL);
375                 if (!addrs)
376                         return -ENOMEM;
377         }
378
379 do_pass:
380         new_insn = new_prog;
381         fp = prog;
382
383         if (new_insn)
384                 *new_insn = BPF_MOV64_REG(BPF_REG_CTX, BPF_REG_ARG1);
385         new_insn++;
386
387         for (i = 0; i < len; fp++, i++) {
388                 struct bpf_insn tmp_insns[6] = { };
389                 struct bpf_insn *insn = tmp_insns;
390
391                 if (addrs)
392                         addrs[i] = new_insn - new_prog;
393
394                 switch (fp->code) {
395                 /* All arithmetic insns and skb loads map as-is. */
396                 case BPF_ALU | BPF_ADD | BPF_X:
397                 case BPF_ALU | BPF_ADD | BPF_K:
398                 case BPF_ALU | BPF_SUB | BPF_X:
399                 case BPF_ALU | BPF_SUB | BPF_K:
400                 case BPF_ALU | BPF_AND | BPF_X:
401                 case BPF_ALU | BPF_AND | BPF_K:
402                 case BPF_ALU | BPF_OR | BPF_X:
403                 case BPF_ALU | BPF_OR | BPF_K:
404                 case BPF_ALU | BPF_LSH | BPF_X:
405                 case BPF_ALU | BPF_LSH | BPF_K:
406                 case BPF_ALU | BPF_RSH | BPF_X:
407                 case BPF_ALU | BPF_RSH | BPF_K:
408                 case BPF_ALU | BPF_XOR | BPF_X:
409                 case BPF_ALU | BPF_XOR | BPF_K:
410                 case BPF_ALU | BPF_MUL | BPF_X:
411                 case BPF_ALU | BPF_MUL | BPF_K:
412                 case BPF_ALU | BPF_DIV | BPF_X:
413                 case BPF_ALU | BPF_DIV | BPF_K:
414                 case BPF_ALU | BPF_MOD | BPF_X:
415                 case BPF_ALU | BPF_MOD | BPF_K:
416                 case BPF_ALU | BPF_NEG:
417                 case BPF_LD | BPF_ABS | BPF_W:
418                 case BPF_LD | BPF_ABS | BPF_H:
419                 case BPF_LD | BPF_ABS | BPF_B:
420                 case BPF_LD | BPF_IND | BPF_W:
421                 case BPF_LD | BPF_IND | BPF_H:
422                 case BPF_LD | BPF_IND | BPF_B:
423                         /* Check for overloaded BPF extension and
424                          * directly convert it if found, otherwise
425                          * just move on with mapping.
426                          */
427                         if (BPF_CLASS(fp->code) == BPF_LD &&
428                             BPF_MODE(fp->code) == BPF_ABS &&
429                             convert_bpf_extensions(fp, &insn))
430                                 break;
431
432                         *insn = BPF_RAW_INSN(fp->code, BPF_REG_A, BPF_REG_X, 0, fp->k);
433                         break;
434
435                 /* Jump transformation cannot use BPF block macros
436                  * everywhere as offset calculation and target updates
437                  * require a bit more work than the rest, i.e. jump
438                  * opcodes map as-is, but offsets need adjustment.
439                  */
440
441 #define BPF_EMIT_JMP                                                    \
442         do {                                                            \
443                 if (target >= len || target < 0)                        \
444                         goto err;                                       \
445                 insn->off = addrs ? addrs[target] - addrs[i] - 1 : 0;   \
446                 /* Adjust pc relative offset for 2nd or 3rd insn. */    \
447                 insn->off -= insn - tmp_insns;                          \
448         } while (0)
449
450                 case BPF_JMP | BPF_JA:
451                         target = i + fp->k + 1;
452                         insn->code = fp->code;
453                         BPF_EMIT_JMP;
454                         break;
455
456                 case BPF_JMP | BPF_JEQ | BPF_K:
457                 case BPF_JMP | BPF_JEQ | BPF_X:
458                 case BPF_JMP | BPF_JSET | BPF_K:
459                 case BPF_JMP | BPF_JSET | BPF_X:
460                 case BPF_JMP | BPF_JGT | BPF_K:
461                 case BPF_JMP | BPF_JGT | BPF_X:
462                 case BPF_JMP | BPF_JGE | BPF_K:
463                 case BPF_JMP | BPF_JGE | BPF_X:
464                         if (BPF_SRC(fp->code) == BPF_K && (int) fp->k < 0) {
465                                 /* BPF immediates are signed, zero extend
466                                  * immediate into tmp register and use it
467                                  * in compare insn.
468                                  */
469                                 *insn++ = BPF_MOV32_IMM(BPF_REG_TMP, fp->k);
470
471                                 insn->dst_reg = BPF_REG_A;
472                                 insn->src_reg = BPF_REG_TMP;
473                                 bpf_src = BPF_X;
474                         } else {
475                                 insn->dst_reg = BPF_REG_A;
476                                 insn->src_reg = BPF_REG_X;
477                                 insn->imm = fp->k;
478                                 bpf_src = BPF_SRC(fp->code);
479                         }
480
481                         /* Common case where 'jump_false' is next insn. */
482                         if (fp->jf == 0) {
483                                 insn->code = BPF_JMP | BPF_OP(fp->code) | bpf_src;
484                                 target = i + fp->jt + 1;
485                                 BPF_EMIT_JMP;
486                                 break;
487                         }
488
489                         /* Convert JEQ into JNE when 'jump_true' is next insn. */
490                         if (fp->jt == 0 && BPF_OP(fp->code) == BPF_JEQ) {
491                                 insn->code = BPF_JMP | BPF_JNE | bpf_src;
492                                 target = i + fp->jf + 1;
493                                 BPF_EMIT_JMP;
494                                 break;
495                         }
496
497                         /* Other jumps are mapped into two insns: Jxx and JA. */
498                         target = i + fp->jt + 1;
499                         insn->code = BPF_JMP | BPF_OP(fp->code) | bpf_src;
500                         BPF_EMIT_JMP;
501                         insn++;
502
503                         insn->code = BPF_JMP | BPF_JA;
504                         target = i + fp->jf + 1;
505                         BPF_EMIT_JMP;
506                         break;
507
508                 /* ldxb 4 * ([14] & 0xf) is remaped into 6 insns. */
509                 case BPF_LDX | BPF_MSH | BPF_B:
510                         /* tmp = A */
511                         *insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_A);
512                         /* A = BPF_R0 = *(u8 *) (skb->data + K) */
513                         *insn++ = BPF_LD_ABS(BPF_B, fp->k);
514                         /* A &= 0xf */
515                         *insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_A, 0xf);
516                         /* A <<= 2 */
517                         *insn++ = BPF_ALU32_IMM(BPF_LSH, BPF_REG_A, 2);
518                         /* X = A */
519                         *insn++ = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
520                         /* A = tmp */
521                         *insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_TMP);
522                         break;
523
524                 /* RET_K, RET_A are remaped into 2 insns. */
525                 case BPF_RET | BPF_A:
526                 case BPF_RET | BPF_K:
527                         *insn++ = BPF_MOV32_RAW(BPF_RVAL(fp->code) == BPF_K ?
528                                                 BPF_K : BPF_X, BPF_REG_0,
529                                                 BPF_REG_A, fp->k);
530                         *insn = BPF_EXIT_INSN();
531                         break;
532
533                 /* Store to stack. */
534                 case BPF_ST:
535                 case BPF_STX:
536                         *insn = BPF_STX_MEM(BPF_W, BPF_REG_FP, BPF_CLASS(fp->code) ==
537                                             BPF_ST ? BPF_REG_A : BPF_REG_X,
538                                             -(BPF_MEMWORDS - fp->k) * 4);
539                         break;
540
541                 /* Load from stack. */
542                 case BPF_LD | BPF_MEM:
543                 case BPF_LDX | BPF_MEM:
544                         *insn = BPF_LDX_MEM(BPF_W, BPF_CLASS(fp->code) == BPF_LD  ?
545                                             BPF_REG_A : BPF_REG_X, BPF_REG_FP,
546                                             -(BPF_MEMWORDS - fp->k) * 4);
547                         break;
548
549                 /* A = K or X = K */
550                 case BPF_LD | BPF_IMM:
551                 case BPF_LDX | BPF_IMM:
552                         *insn = BPF_MOV32_IMM(BPF_CLASS(fp->code) == BPF_LD ?
553                                               BPF_REG_A : BPF_REG_X, fp->k);
554                         break;
555
556                 /* X = A */
557                 case BPF_MISC | BPF_TAX:
558                         *insn = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
559                         break;
560
561                 /* A = X */
562                 case BPF_MISC | BPF_TXA:
563                         *insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_X);
564                         break;
565
566                 /* A = skb->len or X = skb->len */
567                 case BPF_LD | BPF_W | BPF_LEN:
568                 case BPF_LDX | BPF_W | BPF_LEN:
569                         *insn = BPF_LDX_MEM(BPF_W, BPF_CLASS(fp->code) == BPF_LD ?
570                                             BPF_REG_A : BPF_REG_X, BPF_REG_CTX,
571                                             offsetof(struct sk_buff, len));
572                         break;
573
574                 /* Access seccomp_data fields. */
575                 case BPF_LDX | BPF_ABS | BPF_W:
576                         /* A = *(u32 *) (ctx + K) */
577                         *insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX, fp->k);
578                         break;
579
580                 /* Unknown instruction. */
581                 default:
582                         goto err;
583                 }
584
585                 insn++;
586                 if (new_prog)
587                         memcpy(new_insn, tmp_insns,
588                                sizeof(*insn) * (insn - tmp_insns));
589                 new_insn += insn - tmp_insns;
590         }
591
592         if (!new_prog) {
593                 /* Only calculating new length. */
594                 *new_len = new_insn - new_prog;
595                 return 0;
596         }
597
598         pass++;
599         if (new_flen != new_insn - new_prog) {
600                 new_flen = new_insn - new_prog;
601                 if (pass > 2)
602                         goto err;
603                 goto do_pass;
604         }
605
606         kfree(addrs);
607         BUG_ON(*new_len != new_flen);
608         return 0;
609 err:
610         kfree(addrs);
611         return -EINVAL;
612 }
613
614 /* Security:
615  *
616  * As we dont want to clear mem[] array for each packet going through
617  * __bpf_prog_run(), we check that filter loaded by user never try to read
618  * a cell if not previously written, and we check all branches to be sure
619  * a malicious user doesn't try to abuse us.
620  */
621 static int check_load_and_stores(const struct sock_filter *filter, int flen)
622 {
623         u16 *masks, memvalid = 0; /* One bit per cell, 16 cells */
624         int pc, ret = 0;
625
626         BUILD_BUG_ON(BPF_MEMWORDS > 16);
627
628         masks = kmalloc_array(flen, sizeof(*masks), GFP_KERNEL);
629         if (!masks)
630                 return -ENOMEM;
631
632         memset(masks, 0xff, flen * sizeof(*masks));
633
634         for (pc = 0; pc < flen; pc++) {
635                 memvalid &= masks[pc];
636
637                 switch (filter[pc].code) {
638                 case BPF_ST:
639                 case BPF_STX:
640                         memvalid |= (1 << filter[pc].k);
641                         break;
642                 case BPF_LD | BPF_MEM:
643                 case BPF_LDX | BPF_MEM:
644                         if (!(memvalid & (1 << filter[pc].k))) {
645                                 ret = -EINVAL;
646                                 goto error;
647                         }
648                         break;
649                 case BPF_JMP | BPF_JA:
650                         /* A jump must set masks on target */
651                         masks[pc + 1 + filter[pc].k] &= memvalid;
652                         memvalid = ~0;
653                         break;
654                 case BPF_JMP | BPF_JEQ | BPF_K:
655                 case BPF_JMP | BPF_JEQ | BPF_X:
656                 case BPF_JMP | BPF_JGE | BPF_K:
657                 case BPF_JMP | BPF_JGE | BPF_X:
658                 case BPF_JMP | BPF_JGT | BPF_K:
659                 case BPF_JMP | BPF_JGT | BPF_X:
660                 case BPF_JMP | BPF_JSET | BPF_K:
661                 case BPF_JMP | BPF_JSET | BPF_X:
662                         /* A jump must set masks on targets */
663                         masks[pc + 1 + filter[pc].jt] &= memvalid;
664                         masks[pc + 1 + filter[pc].jf] &= memvalid;
665                         memvalid = ~0;
666                         break;
667                 }
668         }
669 error:
670         kfree(masks);
671         return ret;
672 }
673
674 static bool chk_code_allowed(u16 code_to_probe)
675 {
676         static const bool codes[] = {
677                 /* 32 bit ALU operations */
678                 [BPF_ALU | BPF_ADD | BPF_K] = true,
679                 [BPF_ALU | BPF_ADD | BPF_X] = true,
680                 [BPF_ALU | BPF_SUB | BPF_K] = true,
681                 [BPF_ALU | BPF_SUB | BPF_X] = true,
682                 [BPF_ALU | BPF_MUL | BPF_K] = true,
683                 [BPF_ALU | BPF_MUL | BPF_X] = true,
684                 [BPF_ALU | BPF_DIV | BPF_K] = true,
685                 [BPF_ALU | BPF_DIV | BPF_X] = true,
686                 [BPF_ALU | BPF_MOD | BPF_K] = true,
687                 [BPF_ALU | BPF_MOD | BPF_X] = true,
688                 [BPF_ALU | BPF_AND | BPF_K] = true,
689                 [BPF_ALU | BPF_AND | BPF_X] = true,
690                 [BPF_ALU | BPF_OR | BPF_K] = true,
691                 [BPF_ALU | BPF_OR | BPF_X] = true,
692                 [BPF_ALU | BPF_XOR | BPF_K] = true,
693                 [BPF_ALU | BPF_XOR | BPF_X] = true,
694                 [BPF_ALU | BPF_LSH | BPF_K] = true,
695                 [BPF_ALU | BPF_LSH | BPF_X] = true,
696                 [BPF_ALU | BPF_RSH | BPF_K] = true,
697                 [BPF_ALU | BPF_RSH | BPF_X] = true,
698                 [BPF_ALU | BPF_NEG] = true,
699                 /* Load instructions */
700                 [BPF_LD | BPF_W | BPF_ABS] = true,
701                 [BPF_LD | BPF_H | BPF_ABS] = true,
702                 [BPF_LD | BPF_B | BPF_ABS] = true,
703                 [BPF_LD | BPF_W | BPF_LEN] = true,
704                 [BPF_LD | BPF_W | BPF_IND] = true,
705                 [BPF_LD | BPF_H | BPF_IND] = true,
706                 [BPF_LD | BPF_B | BPF_IND] = true,
707                 [BPF_LD | BPF_IMM] = true,
708                 [BPF_LD | BPF_MEM] = true,
709                 [BPF_LDX | BPF_W | BPF_LEN] = true,
710                 [BPF_LDX | BPF_B | BPF_MSH] = true,
711                 [BPF_LDX | BPF_IMM] = true,
712                 [BPF_LDX | BPF_MEM] = true,
713                 /* Store instructions */
714                 [BPF_ST] = true,
715                 [BPF_STX] = true,
716                 /* Misc instructions */
717                 [BPF_MISC | BPF_TAX] = true,
718                 [BPF_MISC | BPF_TXA] = true,
719                 /* Return instructions */
720                 [BPF_RET | BPF_K] = true,
721                 [BPF_RET | BPF_A] = true,
722                 /* Jump instructions */
723                 [BPF_JMP | BPF_JA] = true,
724                 [BPF_JMP | BPF_JEQ | BPF_K] = true,
725                 [BPF_JMP | BPF_JEQ | BPF_X] = true,
726                 [BPF_JMP | BPF_JGE | BPF_K] = true,
727                 [BPF_JMP | BPF_JGE | BPF_X] = true,
728                 [BPF_JMP | BPF_JGT | BPF_K] = true,
729                 [BPF_JMP | BPF_JGT | BPF_X] = true,
730                 [BPF_JMP | BPF_JSET | BPF_K] = true,
731                 [BPF_JMP | BPF_JSET | BPF_X] = true,
732         };
733
734         if (code_to_probe >= ARRAY_SIZE(codes))
735                 return false;
736
737         return codes[code_to_probe];
738 }
739
740 /**
741  *      bpf_check_classic - verify socket filter code
742  *      @filter: filter to verify
743  *      @flen: length of filter
744  *
745  * Check the user's filter code. If we let some ugly
746  * filter code slip through kaboom! The filter must contain
747  * no references or jumps that are out of range, no illegal
748  * instructions, and must end with a RET instruction.
749  *
750  * All jumps are forward as they are not signed.
751  *
752  * Returns 0 if the rule set is legal or -EINVAL if not.
753  */
754 int bpf_check_classic(const struct sock_filter *filter, unsigned int flen)
755 {
756         bool anc_found;
757         int pc;
758
759         if (flen == 0 || flen > BPF_MAXINSNS)
760                 return -EINVAL;
761
762         /* Check the filter code now */
763         for (pc = 0; pc < flen; pc++) {
764                 const struct sock_filter *ftest = &filter[pc];
765
766                 /* May we actually operate on this code? */
767                 if (!chk_code_allowed(ftest->code))
768                         return -EINVAL;
769
770                 /* Some instructions need special checks */
771                 switch (ftest->code) {
772                 case BPF_ALU | BPF_DIV | BPF_K:
773                 case BPF_ALU | BPF_MOD | BPF_K:
774                         /* Check for division by zero */
775                         if (ftest->k == 0)
776                                 return -EINVAL;
777                         break;
778                 case BPF_LD | BPF_MEM:
779                 case BPF_LDX | BPF_MEM:
780                 case BPF_ST:
781                 case BPF_STX:
782                         /* Check for invalid memory addresses */
783                         if (ftest->k >= BPF_MEMWORDS)
784                                 return -EINVAL;
785                         break;
786                 case BPF_JMP | BPF_JA:
787                         /* Note, the large ftest->k might cause loops.
788                          * Compare this with conditional jumps below,
789                          * where offsets are limited. --ANK (981016)
790                          */
791                         if (ftest->k >= (unsigned int)(flen - pc - 1))
792                                 return -EINVAL;
793                         break;
794                 case BPF_JMP | BPF_JEQ | BPF_K:
795                 case BPF_JMP | BPF_JEQ | BPF_X:
796                 case BPF_JMP | BPF_JGE | BPF_K:
797                 case BPF_JMP | BPF_JGE | BPF_X:
798                 case BPF_JMP | BPF_JGT | BPF_K:
799                 case BPF_JMP | BPF_JGT | BPF_X:
800                 case BPF_JMP | BPF_JSET | BPF_K:
801                 case BPF_JMP | BPF_JSET | BPF_X:
802                         /* Both conditionals must be safe */
803                         if (pc + ftest->jt + 1 >= flen ||
804                             pc + ftest->jf + 1 >= flen)
805                                 return -EINVAL;
806                         break;
807                 case BPF_LD | BPF_W | BPF_ABS:
808                 case BPF_LD | BPF_H | BPF_ABS:
809                 case BPF_LD | BPF_B | BPF_ABS:
810                         anc_found = false;
811                         if (bpf_anc_helper(ftest) & BPF_ANC)
812                                 anc_found = true;
813                         /* Ancillary operation unknown or unsupported */
814                         if (anc_found == false && ftest->k >= SKF_AD_OFF)
815                                 return -EINVAL;
816                 }
817         }
818
819         /* Last instruction must be a RET code */
820         switch (filter[flen - 1].code) {
821         case BPF_RET | BPF_K:
822         case BPF_RET | BPF_A:
823                 return check_load_and_stores(filter, flen);
824         }
825
826         return -EINVAL;
827 }
828 EXPORT_SYMBOL(bpf_check_classic);
829
830 static int bpf_prog_store_orig_filter(struct bpf_prog *fp,
831                                       const struct sock_fprog *fprog)
832 {
833         unsigned int fsize = bpf_classic_proglen(fprog);
834         struct sock_fprog_kern *fkprog;
835
836         fp->orig_prog = kmalloc(sizeof(*fkprog), GFP_KERNEL);
837         if (!fp->orig_prog)
838                 return -ENOMEM;
839
840         fkprog = fp->orig_prog;
841         fkprog->len = fprog->len;
842         fkprog->filter = kmemdup(fp->insns, fsize, GFP_KERNEL);
843         if (!fkprog->filter) {
844                 kfree(fp->orig_prog);
845                 return -ENOMEM;
846         }
847
848         return 0;
849 }
850
851 static void bpf_release_orig_filter(struct bpf_prog *fp)
852 {
853         struct sock_fprog_kern *fprog = fp->orig_prog;
854
855         if (fprog) {
856                 kfree(fprog->filter);
857                 kfree(fprog);
858         }
859 }
860
861 static void __bpf_prog_release(struct bpf_prog *prog)
862 {
863         if (prog->type == BPF_PROG_TYPE_SOCKET_FILTER) {
864                 bpf_prog_put(prog);
865         } else {
866                 bpf_release_orig_filter(prog);
867                 bpf_prog_free(prog);
868         }
869 }
870
871 static void __sk_filter_release(struct sk_filter *fp)
872 {
873         __bpf_prog_release(fp->prog);
874         kfree(fp);
875 }
876
877 /**
878  *      sk_filter_release_rcu - Release a socket filter by rcu_head
879  *      @rcu: rcu_head that contains the sk_filter to free
880  */
881 static void sk_filter_release_rcu(struct rcu_head *rcu)
882 {
883         struct sk_filter *fp = container_of(rcu, struct sk_filter, rcu);
884
885         __sk_filter_release(fp);
886 }
887
888 /**
889  *      sk_filter_release - release a socket filter
890  *      @fp: filter to remove
891  *
892  *      Remove a filter from a socket and release its resources.
893  */
894 static void sk_filter_release(struct sk_filter *fp)
895 {
896         if (atomic_dec_and_test(&fp->refcnt))
897                 call_rcu(&fp->rcu, sk_filter_release_rcu);
898 }
899
900 void sk_filter_uncharge(struct sock *sk, struct sk_filter *fp)
901 {
902         u32 filter_size = bpf_prog_size(fp->prog->len);
903
904         atomic_sub(filter_size, &sk->sk_omem_alloc);
905         sk_filter_release(fp);
906 }
907
908 /* try to charge the socket memory if there is space available
909  * return true on success
910  */
911 bool sk_filter_charge(struct sock *sk, struct sk_filter *fp)
912 {
913         u32 filter_size = bpf_prog_size(fp->prog->len);
914
915         /* same check as in sock_kmalloc() */
916         if (filter_size <= sysctl_optmem_max &&
917             atomic_read(&sk->sk_omem_alloc) + filter_size < sysctl_optmem_max) {
918                 atomic_inc(&fp->refcnt);
919                 atomic_add(filter_size, &sk->sk_omem_alloc);
920                 return true;
921         }
922         return false;
923 }
924
925 static struct bpf_prog *bpf_migrate_filter(struct bpf_prog *fp)
926 {
927         struct sock_filter *old_prog;
928         struct bpf_prog *old_fp;
929         int err, new_len, old_len = fp->len;
930
931         /* We are free to overwrite insns et al right here as it
932          * won't be used at this point in time anymore internally
933          * after the migration to the internal BPF instruction
934          * representation.
935          */
936         BUILD_BUG_ON(sizeof(struct sock_filter) !=
937                      sizeof(struct bpf_insn));
938
939         /* Conversion cannot happen on overlapping memory areas,
940          * so we need to keep the user BPF around until the 2nd
941          * pass. At this time, the user BPF is stored in fp->insns.
942          */
943         old_prog = kmemdup(fp->insns, old_len * sizeof(struct sock_filter),
944                            GFP_KERNEL);
945         if (!old_prog) {
946                 err = -ENOMEM;
947                 goto out_err;
948         }
949
950         /* 1st pass: calculate the new program length. */
951         err = bpf_convert_filter(old_prog, old_len, NULL, &new_len);
952         if (err)
953                 goto out_err_free;
954
955         /* Expand fp for appending the new filter representation. */
956         old_fp = fp;
957         fp = bpf_prog_realloc(old_fp, bpf_prog_size(new_len), 0);
958         if (!fp) {
959                 /* The old_fp is still around in case we couldn't
960                  * allocate new memory, so uncharge on that one.
961                  */
962                 fp = old_fp;
963                 err = -ENOMEM;
964                 goto out_err_free;
965         }
966
967         fp->len = new_len;
968
969         /* 2nd pass: remap sock_filter insns into bpf_insn insns. */
970         err = bpf_convert_filter(old_prog, old_len, fp->insnsi, &new_len);
971         if (err)
972                 /* 2nd bpf_convert_filter() can fail only if it fails
973                  * to allocate memory, remapping must succeed. Note,
974                  * that at this time old_fp has already been released
975                  * by krealloc().
976                  */
977                 goto out_err_free;
978
979         bpf_prog_select_runtime(fp);
980
981         kfree(old_prog);
982         return fp;
983
984 out_err_free:
985         kfree(old_prog);
986 out_err:
987         __bpf_prog_release(fp);
988         return ERR_PTR(err);
989 }
990
991 static struct bpf_prog *bpf_prepare_filter(struct bpf_prog *fp)
992 {
993         int err;
994
995         fp->bpf_func = NULL;
996         fp->jited = false;
997
998         err = bpf_check_classic(fp->insns, fp->len);
999         if (err) {
1000                 __bpf_prog_release(fp);
1001                 return ERR_PTR(err);
1002         }
1003
1004         /* Probe if we can JIT compile the filter and if so, do
1005          * the compilation of the filter.
1006          */
1007         bpf_jit_compile(fp);
1008
1009         /* JIT compiler couldn't process this filter, so do the
1010          * internal BPF translation for the optimized interpreter.
1011          */
1012         if (!fp->jited)
1013                 fp = bpf_migrate_filter(fp);
1014
1015         return fp;
1016 }
1017
1018 /**
1019  *      bpf_prog_create - create an unattached filter
1020  *      @pfp: the unattached filter that is created
1021  *      @fprog: the filter program
1022  *
1023  * Create a filter independent of any socket. We first run some
1024  * sanity checks on it to make sure it does not explode on us later.
1025  * If an error occurs or there is insufficient memory for the filter
1026  * a negative errno code is returned. On success the return is zero.
1027  */
1028 int bpf_prog_create(struct bpf_prog **pfp, struct sock_fprog_kern *fprog)
1029 {
1030         unsigned int fsize = bpf_classic_proglen(fprog);
1031         struct bpf_prog *fp;
1032
1033         /* Make sure new filter is there and in the right amounts. */
1034         if (fprog->filter == NULL)
1035                 return -EINVAL;
1036
1037         fp = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1038         if (!fp)
1039                 return -ENOMEM;
1040
1041         memcpy(fp->insns, fprog->filter, fsize);
1042
1043         fp->len = fprog->len;
1044         /* Since unattached filters are not copied back to user
1045          * space through sk_get_filter(), we do not need to hold
1046          * a copy here, and can spare us the work.
1047          */
1048         fp->orig_prog = NULL;
1049
1050         /* bpf_prepare_filter() already takes care of freeing
1051          * memory in case something goes wrong.
1052          */
1053         fp = bpf_prepare_filter(fp);
1054         if (IS_ERR(fp))
1055                 return PTR_ERR(fp);
1056
1057         *pfp = fp;
1058         return 0;
1059 }
1060 EXPORT_SYMBOL_GPL(bpf_prog_create);
1061
1062 void bpf_prog_destroy(struct bpf_prog *fp)
1063 {
1064         __bpf_prog_release(fp);
1065 }
1066 EXPORT_SYMBOL_GPL(bpf_prog_destroy);
1067
1068 static int __sk_attach_prog(struct bpf_prog *prog, struct sock *sk)
1069 {
1070         struct sk_filter *fp, *old_fp;
1071
1072         fp = kmalloc(sizeof(*fp), GFP_KERNEL);
1073         if (!fp)
1074                 return -ENOMEM;
1075
1076         fp->prog = prog;
1077         atomic_set(&fp->refcnt, 0);
1078
1079         if (!sk_filter_charge(sk, fp)) {
1080                 kfree(fp);
1081                 return -ENOMEM;
1082         }
1083
1084         old_fp = rcu_dereference_protected(sk->sk_filter,
1085                                            sock_owned_by_user(sk));
1086         rcu_assign_pointer(sk->sk_filter, fp);
1087
1088         if (old_fp)
1089                 sk_filter_uncharge(sk, old_fp);
1090
1091         return 0;
1092 }
1093
1094 /**
1095  *      sk_attach_filter - attach a socket filter
1096  *      @fprog: the filter program
1097  *      @sk: the socket to use
1098  *
1099  * Attach the user's filter code. We first run some sanity checks on
1100  * it to make sure it does not explode on us later. If an error
1101  * occurs or there is insufficient memory for the filter a negative
1102  * errno code is returned. On success the return is zero.
1103  */
1104 int sk_attach_filter(struct sock_fprog *fprog, struct sock *sk)
1105 {
1106         unsigned int fsize = bpf_classic_proglen(fprog);
1107         unsigned int bpf_fsize = bpf_prog_size(fprog->len);
1108         struct bpf_prog *prog;
1109         int err;
1110
1111         if (sock_flag(sk, SOCK_FILTER_LOCKED))
1112                 return -EPERM;
1113
1114         /* Make sure new filter is there and in the right amounts. */
1115         if (fprog->filter == NULL)
1116                 return -EINVAL;
1117
1118         prog = bpf_prog_alloc(bpf_fsize, 0);
1119         if (!prog)
1120                 return -ENOMEM;
1121
1122         if (copy_from_user(prog->insns, fprog->filter, fsize)) {
1123                 __bpf_prog_free(prog);
1124                 return -EFAULT;
1125         }
1126
1127         prog->len = fprog->len;
1128
1129         err = bpf_prog_store_orig_filter(prog, fprog);
1130         if (err) {
1131                 __bpf_prog_free(prog);
1132                 return -ENOMEM;
1133         }
1134
1135         /* bpf_prepare_filter() already takes care of freeing
1136          * memory in case something goes wrong.
1137          */
1138         prog = bpf_prepare_filter(prog);
1139         if (IS_ERR(prog))
1140                 return PTR_ERR(prog);
1141
1142         err = __sk_attach_prog(prog, sk);
1143         if (err < 0) {
1144                 __bpf_prog_release(prog);
1145                 return err;
1146         }
1147
1148         return 0;
1149 }
1150 EXPORT_SYMBOL_GPL(sk_attach_filter);
1151
1152 int sk_attach_bpf(u32 ufd, struct sock *sk)
1153 {
1154         struct bpf_prog *prog;
1155         int err;
1156
1157         if (sock_flag(sk, SOCK_FILTER_LOCKED))
1158                 return -EPERM;
1159
1160         prog = bpf_prog_get(ufd);
1161         if (IS_ERR(prog))
1162                 return PTR_ERR(prog);
1163
1164         if (prog->type != BPF_PROG_TYPE_SOCKET_FILTER) {
1165                 bpf_prog_put(prog);
1166                 return -EINVAL;
1167         }
1168
1169         err = __sk_attach_prog(prog, sk);
1170         if (err < 0) {
1171                 bpf_prog_put(prog);
1172                 return err;
1173         }
1174
1175         return 0;
1176 }
1177
1178 #define BPF_RECOMPUTE_CSUM(flags)       ((flags) & 1)
1179
1180 static u64 bpf_skb_store_bytes(u64 r1, u64 r2, u64 r3, u64 r4, u64 flags)
1181 {
1182         struct sk_buff *skb = (struct sk_buff *) (long) r1;
1183         unsigned int offset = (unsigned int) r2;
1184         void *from = (void *) (long) r3;
1185         unsigned int len = (unsigned int) r4;
1186         char buf[16];
1187         void *ptr;
1188
1189         /* bpf verifier guarantees that:
1190          * 'from' pointer points to bpf program stack
1191          * 'len' bytes of it were initialized
1192          * 'len' > 0
1193          * 'skb' is a valid pointer to 'struct sk_buff'
1194          *
1195          * so check for invalid 'offset' and too large 'len'
1196          */
1197         if (unlikely(offset > 0xffff || len > sizeof(buf)))
1198                 return -EFAULT;
1199
1200         if (skb_cloned(skb) && !skb_clone_writable(skb, offset + len))
1201                 return -EFAULT;
1202
1203         ptr = skb_header_pointer(skb, offset, len, buf);
1204         if (unlikely(!ptr))
1205                 return -EFAULT;
1206
1207         if (BPF_RECOMPUTE_CSUM(flags))
1208                 skb_postpull_rcsum(skb, ptr, len);
1209
1210         memcpy(ptr, from, len);
1211
1212         if (ptr == buf)
1213                 /* skb_store_bits cannot return -EFAULT here */
1214                 skb_store_bits(skb, offset, ptr, len);
1215
1216         if (BPF_RECOMPUTE_CSUM(flags) && skb->ip_summed == CHECKSUM_COMPLETE)
1217                 skb->csum = csum_add(skb->csum, csum_partial(ptr, len, 0));
1218         return 0;
1219 }
1220
1221 const struct bpf_func_proto bpf_skb_store_bytes_proto = {
1222         .func           = bpf_skb_store_bytes,
1223         .gpl_only       = false,
1224         .ret_type       = RET_INTEGER,
1225         .arg1_type      = ARG_PTR_TO_CTX,
1226         .arg2_type      = ARG_ANYTHING,
1227         .arg3_type      = ARG_PTR_TO_STACK,
1228         .arg4_type      = ARG_CONST_STACK_SIZE,
1229         .arg5_type      = ARG_ANYTHING,
1230 };
1231
1232 #define BPF_HEADER_FIELD_SIZE(flags)    ((flags) & 0x0f)
1233 #define BPF_IS_PSEUDO_HEADER(flags)     ((flags) & 0x10)
1234
1235 static u64 bpf_l3_csum_replace(u64 r1, u64 offset, u64 from, u64 to, u64 flags)
1236 {
1237         struct sk_buff *skb = (struct sk_buff *) (long) r1;
1238         __sum16 sum, *ptr;
1239
1240         if (unlikely(offset > 0xffff))
1241                 return -EFAULT;
1242
1243         if (skb_cloned(skb) && !skb_clone_writable(skb, offset + sizeof(sum)))
1244                 return -EFAULT;
1245
1246         ptr = skb_header_pointer(skb, offset, sizeof(sum), &sum);
1247         if (unlikely(!ptr))
1248                 return -EFAULT;
1249
1250         switch (BPF_HEADER_FIELD_SIZE(flags)) {
1251         case 2:
1252                 csum_replace2(ptr, from, to);
1253                 break;
1254         case 4:
1255                 csum_replace4(ptr, from, to);
1256                 break;
1257         default:
1258                 return -EINVAL;
1259         }
1260
1261         if (ptr == &sum)
1262                 /* skb_store_bits guaranteed to not return -EFAULT here */
1263                 skb_store_bits(skb, offset, ptr, sizeof(sum));
1264
1265         return 0;
1266 }
1267
1268 const struct bpf_func_proto bpf_l3_csum_replace_proto = {
1269         .func           = bpf_l3_csum_replace,
1270         .gpl_only       = false,
1271         .ret_type       = RET_INTEGER,
1272         .arg1_type      = ARG_PTR_TO_CTX,
1273         .arg2_type      = ARG_ANYTHING,
1274         .arg3_type      = ARG_ANYTHING,
1275         .arg4_type      = ARG_ANYTHING,
1276         .arg5_type      = ARG_ANYTHING,
1277 };
1278
1279 static u64 bpf_l4_csum_replace(u64 r1, u64 offset, u64 from, u64 to, u64 flags)
1280 {
1281         struct sk_buff *skb = (struct sk_buff *) (long) r1;
1282         u32 is_pseudo = BPF_IS_PSEUDO_HEADER(flags);
1283         __sum16 sum, *ptr;
1284
1285         if (unlikely(offset > 0xffff))
1286                 return -EFAULT;
1287
1288         if (skb_cloned(skb) && !skb_clone_writable(skb, offset + sizeof(sum)))
1289                 return -EFAULT;
1290
1291         ptr = skb_header_pointer(skb, offset, sizeof(sum), &sum);
1292         if (unlikely(!ptr))
1293                 return -EFAULT;
1294
1295         switch (BPF_HEADER_FIELD_SIZE(flags)) {
1296         case 2:
1297                 inet_proto_csum_replace2(ptr, skb, from, to, is_pseudo);
1298                 break;
1299         case 4:
1300                 inet_proto_csum_replace4(ptr, skb, from, to, is_pseudo);
1301                 break;
1302         default:
1303                 return -EINVAL;
1304         }
1305
1306         if (ptr == &sum)
1307                 /* skb_store_bits guaranteed to not return -EFAULT here */
1308                 skb_store_bits(skb, offset, ptr, sizeof(sum));
1309
1310         return 0;
1311 }
1312
1313 const struct bpf_func_proto bpf_l4_csum_replace_proto = {
1314         .func           = bpf_l4_csum_replace,
1315         .gpl_only       = false,
1316         .ret_type       = RET_INTEGER,
1317         .arg1_type      = ARG_PTR_TO_CTX,
1318         .arg2_type      = ARG_ANYTHING,
1319         .arg3_type      = ARG_ANYTHING,
1320         .arg4_type      = ARG_ANYTHING,
1321         .arg5_type      = ARG_ANYTHING,
1322 };
1323
1324 static const struct bpf_func_proto *
1325 sk_filter_func_proto(enum bpf_func_id func_id)
1326 {
1327         switch (func_id) {
1328         case BPF_FUNC_map_lookup_elem:
1329                 return &bpf_map_lookup_elem_proto;
1330         case BPF_FUNC_map_update_elem:
1331                 return &bpf_map_update_elem_proto;
1332         case BPF_FUNC_map_delete_elem:
1333                 return &bpf_map_delete_elem_proto;
1334         case BPF_FUNC_get_prandom_u32:
1335                 return &bpf_get_prandom_u32_proto;
1336         case BPF_FUNC_get_smp_processor_id:
1337                 return &bpf_get_smp_processor_id_proto;
1338         default:
1339                 return NULL;
1340         }
1341 }
1342
1343 static const struct bpf_func_proto *
1344 tc_cls_act_func_proto(enum bpf_func_id func_id)
1345 {
1346         switch (func_id) {
1347         case BPF_FUNC_skb_store_bytes:
1348                 return &bpf_skb_store_bytes_proto;
1349         case BPF_FUNC_l3_csum_replace:
1350                 return &bpf_l3_csum_replace_proto;
1351         case BPF_FUNC_l4_csum_replace:
1352                 return &bpf_l4_csum_replace_proto;
1353         default:
1354                 return sk_filter_func_proto(func_id);
1355         }
1356 }
1357
1358 static bool sk_filter_is_valid_access(int off, int size,
1359                                       enum bpf_access_type type)
1360 {
1361         /* only read is allowed */
1362         if (type != BPF_READ)
1363                 return false;
1364
1365         /* check bounds */
1366         if (off < 0 || off >= sizeof(struct __sk_buff))
1367                 return false;
1368
1369         /* disallow misaligned access */
1370         if (off % size != 0)
1371                 return false;
1372
1373         /* all __sk_buff fields are __u32 */
1374         if (size != 4)
1375                 return false;
1376
1377         return true;
1378 }
1379
1380 static u32 sk_filter_convert_ctx_access(int dst_reg, int src_reg, int ctx_off,
1381                                         struct bpf_insn *insn_buf)
1382 {
1383         struct bpf_insn *insn = insn_buf;
1384
1385         switch (ctx_off) {
1386         case offsetof(struct __sk_buff, len):
1387                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, len) != 4);
1388
1389                 *insn++ = BPF_LDX_MEM(BPF_W, dst_reg, src_reg,
1390                                       offsetof(struct sk_buff, len));
1391                 break;
1392
1393         case offsetof(struct __sk_buff, protocol):
1394                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, protocol) != 2);
1395
1396                 *insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
1397                                       offsetof(struct sk_buff, protocol));
1398                 break;
1399
1400         case offsetof(struct __sk_buff, vlan_proto):
1401                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, vlan_proto) != 2);
1402
1403                 *insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
1404                                       offsetof(struct sk_buff, vlan_proto));
1405                 break;
1406
1407         case offsetof(struct __sk_buff, priority):
1408                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, priority) != 4);
1409
1410                 *insn++ = BPF_LDX_MEM(BPF_W, dst_reg, src_reg,
1411                                       offsetof(struct sk_buff, priority));
1412                 break;
1413
1414         case offsetof(struct __sk_buff, mark):
1415                 return convert_skb_access(SKF_AD_MARK, dst_reg, src_reg, insn);
1416
1417         case offsetof(struct __sk_buff, pkt_type):
1418                 return convert_skb_access(SKF_AD_PKTTYPE, dst_reg, src_reg, insn);
1419
1420         case offsetof(struct __sk_buff, queue_mapping):
1421                 return convert_skb_access(SKF_AD_QUEUE, dst_reg, src_reg, insn);
1422
1423         case offsetof(struct __sk_buff, vlan_present):
1424                 return convert_skb_access(SKF_AD_VLAN_TAG_PRESENT,
1425                                           dst_reg, src_reg, insn);
1426
1427         case offsetof(struct __sk_buff, vlan_tci):
1428                 return convert_skb_access(SKF_AD_VLAN_TAG,
1429                                           dst_reg, src_reg, insn);
1430         }
1431
1432         return insn - insn_buf;
1433 }
1434
1435 static const struct bpf_verifier_ops sk_filter_ops = {
1436         .get_func_proto = sk_filter_func_proto,
1437         .is_valid_access = sk_filter_is_valid_access,
1438         .convert_ctx_access = sk_filter_convert_ctx_access,
1439 };
1440
1441 static const struct bpf_verifier_ops tc_cls_act_ops = {
1442         .get_func_proto = tc_cls_act_func_proto,
1443         .is_valid_access = sk_filter_is_valid_access,
1444         .convert_ctx_access = sk_filter_convert_ctx_access,
1445 };
1446
1447 static struct bpf_prog_type_list sk_filter_type __read_mostly = {
1448         .ops = &sk_filter_ops,
1449         .type = BPF_PROG_TYPE_SOCKET_FILTER,
1450 };
1451
1452 static struct bpf_prog_type_list sched_cls_type __read_mostly = {
1453         .ops = &tc_cls_act_ops,
1454         .type = BPF_PROG_TYPE_SCHED_CLS,
1455 };
1456
1457 static struct bpf_prog_type_list sched_act_type __read_mostly = {
1458         .ops = &tc_cls_act_ops,
1459         .type = BPF_PROG_TYPE_SCHED_ACT,
1460 };
1461
1462 static int __init register_sk_filter_ops(void)
1463 {
1464         bpf_register_prog_type(&sk_filter_type);
1465         bpf_register_prog_type(&sched_cls_type);
1466         bpf_register_prog_type(&sched_act_type);
1467
1468         return 0;
1469 }
1470 late_initcall(register_sk_filter_ops);
1471
1472 int sk_detach_filter(struct sock *sk)
1473 {
1474         int ret = -ENOENT;
1475         struct sk_filter *filter;
1476
1477         if (sock_flag(sk, SOCK_FILTER_LOCKED))
1478                 return -EPERM;
1479
1480         filter = rcu_dereference_protected(sk->sk_filter,
1481                                            sock_owned_by_user(sk));
1482         if (filter) {
1483                 RCU_INIT_POINTER(sk->sk_filter, NULL);
1484                 sk_filter_uncharge(sk, filter);
1485                 ret = 0;
1486         }
1487
1488         return ret;
1489 }
1490 EXPORT_SYMBOL_GPL(sk_detach_filter);
1491
1492 int sk_get_filter(struct sock *sk, struct sock_filter __user *ubuf,
1493                   unsigned int len)
1494 {
1495         struct sock_fprog_kern *fprog;
1496         struct sk_filter *filter;
1497         int ret = 0;
1498
1499         lock_sock(sk);
1500         filter = rcu_dereference_protected(sk->sk_filter,
1501                                            sock_owned_by_user(sk));
1502         if (!filter)
1503                 goto out;
1504
1505         /* We're copying the filter that has been originally attached,
1506          * so no conversion/decode needed anymore.
1507          */
1508         fprog = filter->prog->orig_prog;
1509
1510         ret = fprog->len;
1511         if (!len)
1512                 /* User space only enquires number of filter blocks. */
1513                 goto out;
1514
1515         ret = -EINVAL;
1516         if (len < fprog->len)
1517                 goto out;
1518
1519         ret = -EFAULT;
1520         if (copy_to_user(ubuf, fprog->filter, bpf_classic_proglen(fprog)))
1521                 goto out;
1522
1523         /* Instead of bytes, the API requests to return the number
1524          * of filter blocks.
1525          */
1526         ret = fprog->len;
1527 out:
1528         release_sock(sk);
1529         return ret;
1530 }