xref: /openbmc/linux/lib/nlattr.c (revision a17922de)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * NETLINK      Netlink attributes
4  *
5  * 		Authors:	Thomas Graf <tgraf@suug.ch>
6  * 				Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
7  */
8 
9 #include <linux/export.h>
10 #include <linux/kernel.h>
11 #include <linux/errno.h>
12 #include <linux/jiffies.h>
13 #include <linux/skbuff.h>
14 #include <linux/string.h>
15 #include <linux/types.h>
16 #include <net/netlink.h>
17 
18 /* For these data types, attribute length should be exactly the given
19  * size. However, to maintain compatibility with broken commands, if the
20  * attribute length does not match the expected size a warning is emitted
21  * to the user that the command is sending invalid data and needs to be fixed.
22  */
23 static const u8 nla_attr_len[NLA_TYPE_MAX+1] = {
24 	[NLA_U8]	= sizeof(u8),
25 	[NLA_U16]	= sizeof(u16),
26 	[NLA_U32]	= sizeof(u32),
27 	[NLA_U64]	= sizeof(u64),
28 	[NLA_S8]	= sizeof(s8),
29 	[NLA_S16]	= sizeof(s16),
30 	[NLA_S32]	= sizeof(s32),
31 	[NLA_S64]	= sizeof(s64),
32 };
33 
34 static const u8 nla_attr_minlen[NLA_TYPE_MAX+1] = {
35 	[NLA_U8]	= sizeof(u8),
36 	[NLA_U16]	= sizeof(u16),
37 	[NLA_U32]	= sizeof(u32),
38 	[NLA_U64]	= sizeof(u64),
39 	[NLA_MSECS]	= sizeof(u64),
40 	[NLA_NESTED]	= NLA_HDRLEN,
41 	[NLA_S8]	= sizeof(s8),
42 	[NLA_S16]	= sizeof(s16),
43 	[NLA_S32]	= sizeof(s32),
44 	[NLA_S64]	= sizeof(s64),
45 };
46 
47 static int validate_nla_bitfield32(const struct nlattr *nla,
48 				   u32 *valid_flags_allowed)
49 {
50 	const struct nla_bitfield32 *bf = nla_data(nla);
51 	u32 *valid_flags_mask = valid_flags_allowed;
52 
53 	if (!valid_flags_allowed)
54 		return -EINVAL;
55 
56 	/*disallow invalid bit selector */
57 	if (bf->selector & ~*valid_flags_mask)
58 		return -EINVAL;
59 
60 	/*disallow invalid bit values */
61 	if (bf->value & ~*valid_flags_mask)
62 		return -EINVAL;
63 
64 	/*disallow valid bit values that are not selected*/
65 	if (bf->value & ~bf->selector)
66 		return -EINVAL;
67 
68 	return 0;
69 }
70 
71 static int validate_nla(const struct nlattr *nla, int maxtype,
72 			const struct nla_policy *policy)
73 {
74 	const struct nla_policy *pt;
75 	int minlen = 0, attrlen = nla_len(nla), type = nla_type(nla);
76 
77 	if (type <= 0 || type > maxtype)
78 		return 0;
79 
80 	pt = &policy[type];
81 
82 	BUG_ON(pt->type > NLA_TYPE_MAX);
83 
84 	if (nla_attr_len[pt->type] && attrlen != nla_attr_len[pt->type]) {
85 		pr_warn_ratelimited("netlink: '%s': attribute type %d has an invalid length.\n",
86 				    current->comm, type);
87 	}
88 
89 	switch (pt->type) {
90 	case NLA_FLAG:
91 		if (attrlen > 0)
92 			return -ERANGE;
93 		break;
94 
95 	case NLA_BITFIELD32:
96 		if (attrlen != sizeof(struct nla_bitfield32))
97 			return -ERANGE;
98 
99 		return validate_nla_bitfield32(nla, pt->validation_data);
100 
101 	case NLA_NUL_STRING:
102 		if (pt->len)
103 			minlen = min_t(int, attrlen, pt->len + 1);
104 		else
105 			minlen = attrlen;
106 
107 		if (!minlen || memchr(nla_data(nla), '\0', minlen) == NULL)
108 			return -EINVAL;
109 		/* fall through */
110 
111 	case NLA_STRING:
112 		if (attrlen < 1)
113 			return -ERANGE;
114 
115 		if (pt->len) {
116 			char *buf = nla_data(nla);
117 
118 			if (buf[attrlen - 1] == '\0')
119 				attrlen--;
120 
121 			if (attrlen > pt->len)
122 				return -ERANGE;
123 		}
124 		break;
125 
126 	case NLA_BINARY:
127 		if (pt->len && attrlen > pt->len)
128 			return -ERANGE;
129 		break;
130 
131 	case NLA_NESTED_COMPAT:
132 		if (attrlen < pt->len)
133 			return -ERANGE;
134 		if (attrlen < NLA_ALIGN(pt->len))
135 			break;
136 		if (attrlen < NLA_ALIGN(pt->len) + NLA_HDRLEN)
137 			return -ERANGE;
138 		nla = nla_data(nla) + NLA_ALIGN(pt->len);
139 		if (attrlen < NLA_ALIGN(pt->len) + NLA_HDRLEN + nla_len(nla))
140 			return -ERANGE;
141 		break;
142 	case NLA_NESTED:
143 		/* a nested attributes is allowed to be empty; if its not,
144 		 * it must have a size of at least NLA_HDRLEN.
145 		 */
146 		if (attrlen == 0)
147 			break;
148 	default:
149 		if (pt->len)
150 			minlen = pt->len;
151 		else if (pt->type != NLA_UNSPEC)
152 			minlen = nla_attr_minlen[pt->type];
153 
154 		if (attrlen < minlen)
155 			return -ERANGE;
156 	}
157 
158 	return 0;
159 }
160 
161 /**
162  * nla_validate - Validate a stream of attributes
163  * @head: head of attribute stream
164  * @len: length of attribute stream
165  * @maxtype: maximum attribute type to be expected
166  * @policy: validation policy
167  * @extack: extended ACK report struct
168  *
169  * Validates all attributes in the specified attribute stream against the
170  * specified policy. Attributes with a type exceeding maxtype will be
171  * ignored. See documenation of struct nla_policy for more details.
172  *
173  * Returns 0 on success or a negative error code.
174  */
175 int nla_validate(const struct nlattr *head, int len, int maxtype,
176 		 const struct nla_policy *policy,
177 		 struct netlink_ext_ack *extack)
178 {
179 	const struct nlattr *nla;
180 	int rem;
181 
182 	nla_for_each_attr(nla, head, len, rem) {
183 		int err = validate_nla(nla, maxtype, policy);
184 
185 		if (err < 0) {
186 			if (extack)
187 				extack->bad_attr = nla;
188 			return err;
189 		}
190 	}
191 
192 	return 0;
193 }
194 EXPORT_SYMBOL(nla_validate);
195 
196 /**
197  * nla_policy_len - Determin the max. length of a policy
198  * @policy: policy to use
199  * @n: number of policies
200  *
201  * Determines the max. length of the policy.  It is currently used
202  * to allocated Netlink buffers roughly the size of the actual
203  * message.
204  *
205  * Returns 0 on success or a negative error code.
206  */
207 int
208 nla_policy_len(const struct nla_policy *p, int n)
209 {
210 	int i, len = 0;
211 
212 	for (i = 0; i < n; i++, p++) {
213 		if (p->len)
214 			len += nla_total_size(p->len);
215 		else if (nla_attr_len[p->type])
216 			len += nla_total_size(nla_attr_len[p->type]);
217 		else if (nla_attr_minlen[p->type])
218 			len += nla_total_size(nla_attr_minlen[p->type]);
219 	}
220 
221 	return len;
222 }
223 EXPORT_SYMBOL(nla_policy_len);
224 
225 /**
226  * nla_parse - Parse a stream of attributes into a tb buffer
227  * @tb: destination array with maxtype+1 elements
228  * @maxtype: maximum attribute type to be expected
229  * @head: head of attribute stream
230  * @len: length of attribute stream
231  * @policy: validation policy
232  *
233  * Parses a stream of attributes and stores a pointer to each attribute in
234  * the tb array accessible via the attribute type. Attributes with a type
235  * exceeding maxtype will be silently ignored for backwards compatibility
236  * reasons. policy may be set to NULL if no validation is required.
237  *
238  * Returns 0 on success or a negative error code.
239  */
240 int nla_parse(struct nlattr **tb, int maxtype, const struct nlattr *head,
241 	      int len, const struct nla_policy *policy,
242 	      struct netlink_ext_ack *extack)
243 {
244 	const struct nlattr *nla;
245 	int rem, err;
246 
247 	memset(tb, 0, sizeof(struct nlattr *) * (maxtype + 1));
248 
249 	nla_for_each_attr(nla, head, len, rem) {
250 		u16 type = nla_type(nla);
251 
252 		if (type > 0 && type <= maxtype) {
253 			if (policy) {
254 				err = validate_nla(nla, maxtype, policy);
255 				if (err < 0) {
256 					NL_SET_ERR_MSG_ATTR(extack, nla,
257 							    "Attribute failed policy validation");
258 					goto errout;
259 				}
260 			}
261 
262 			tb[type] = (struct nlattr *)nla;
263 		}
264 	}
265 
266 	if (unlikely(rem > 0))
267 		pr_warn_ratelimited("netlink: %d bytes leftover after parsing attributes in process `%s'.\n",
268 				    rem, current->comm);
269 
270 	err = 0;
271 errout:
272 	return err;
273 }
274 EXPORT_SYMBOL(nla_parse);
275 
276 /**
277  * nla_find - Find a specific attribute in a stream of attributes
278  * @head: head of attribute stream
279  * @len: length of attribute stream
280  * @attrtype: type of attribute to look for
281  *
282  * Returns the first attribute in the stream matching the specified type.
283  */
284 struct nlattr *nla_find(const struct nlattr *head, int len, int attrtype)
285 {
286 	const struct nlattr *nla;
287 	int rem;
288 
289 	nla_for_each_attr(nla, head, len, rem)
290 		if (nla_type(nla) == attrtype)
291 			return (struct nlattr *)nla;
292 
293 	return NULL;
294 }
295 EXPORT_SYMBOL(nla_find);
296 
297 /**
298  * nla_strlcpy - Copy string attribute payload into a sized buffer
299  * @dst: where to copy the string to
300  * @nla: attribute to copy the string from
301  * @dstsize: size of destination buffer
302  *
303  * Copies at most dstsize - 1 bytes into the destination buffer.
304  * The result is always a valid NUL-terminated string. Unlike
305  * strlcpy the destination buffer is always padded out.
306  *
307  * Returns the length of the source buffer.
308  */
309 size_t nla_strlcpy(char *dst, const struct nlattr *nla, size_t dstsize)
310 {
311 	size_t srclen = nla_len(nla);
312 	char *src = nla_data(nla);
313 
314 	if (srclen > 0 && src[srclen - 1] == '\0')
315 		srclen--;
316 
317 	if (dstsize > 0) {
318 		size_t len = (srclen >= dstsize) ? dstsize - 1 : srclen;
319 
320 		memset(dst, 0, dstsize);
321 		memcpy(dst, src, len);
322 	}
323 
324 	return srclen;
325 }
326 EXPORT_SYMBOL(nla_strlcpy);
327 
328 /**
329  * nla_strdup - Copy string attribute payload into a newly allocated buffer
330  * @nla: attribute to copy the string from
331  * @flags: the type of memory to allocate (see kmalloc).
332  *
333  * Returns a pointer to the allocated buffer or NULL on error.
334  */
335 char *nla_strdup(const struct nlattr *nla, gfp_t flags)
336 {
337 	size_t srclen = nla_len(nla);
338 	char *src = nla_data(nla), *dst;
339 
340 	if (srclen > 0 && src[srclen - 1] == '\0')
341 		srclen--;
342 
343 	dst = kmalloc(srclen + 1, flags);
344 	if (dst != NULL) {
345 		memcpy(dst, src, srclen);
346 		dst[srclen] = '\0';
347 	}
348 	return dst;
349 }
350 EXPORT_SYMBOL(nla_strdup);
351 
352 /**
353  * nla_memcpy - Copy a netlink attribute into another memory area
354  * @dest: where to copy to memcpy
355  * @src: netlink attribute to copy from
356  * @count: size of the destination area
357  *
358  * Note: The number of bytes copied is limited by the length of
359  *       attribute's payload. memcpy
360  *
361  * Returns the number of bytes copied.
362  */
363 int nla_memcpy(void *dest, const struct nlattr *src, int count)
364 {
365 	int minlen = min_t(int, count, nla_len(src));
366 
367 	memcpy(dest, nla_data(src), minlen);
368 	if (count > minlen)
369 		memset(dest + minlen, 0, count - minlen);
370 
371 	return minlen;
372 }
373 EXPORT_SYMBOL(nla_memcpy);
374 
375 /**
376  * nla_memcmp - Compare an attribute with sized memory area
377  * @nla: netlink attribute
378  * @data: memory area
379  * @size: size of memory area
380  */
381 int nla_memcmp(const struct nlattr *nla, const void *data,
382 			     size_t size)
383 {
384 	int d = nla_len(nla) - size;
385 
386 	if (d == 0)
387 		d = memcmp(nla_data(nla), data, size);
388 
389 	return d;
390 }
391 EXPORT_SYMBOL(nla_memcmp);
392 
393 /**
394  * nla_strcmp - Compare a string attribute against a string
395  * @nla: netlink string attribute
396  * @str: another string
397  */
398 int nla_strcmp(const struct nlattr *nla, const char *str)
399 {
400 	int len = strlen(str);
401 	char *buf = nla_data(nla);
402 	int attrlen = nla_len(nla);
403 	int d;
404 
405 	if (attrlen > 0 && buf[attrlen - 1] == '\0')
406 		attrlen--;
407 
408 	d = attrlen - len;
409 	if (d == 0)
410 		d = memcmp(nla_data(nla), str, len);
411 
412 	return d;
413 }
414 EXPORT_SYMBOL(nla_strcmp);
415 
416 #ifdef CONFIG_NET
417 /**
418  * __nla_reserve - reserve room for attribute on the skb
419  * @skb: socket buffer to reserve room on
420  * @attrtype: attribute type
421  * @attrlen: length of attribute payload
422  *
423  * Adds a netlink attribute header to a socket buffer and reserves
424  * room for the payload but does not copy it.
425  *
426  * The caller is responsible to ensure that the skb provides enough
427  * tailroom for the attribute header and payload.
428  */
429 struct nlattr *__nla_reserve(struct sk_buff *skb, int attrtype, int attrlen)
430 {
431 	struct nlattr *nla;
432 
433 	nla = skb_put(skb, nla_total_size(attrlen));
434 	nla->nla_type = attrtype;
435 	nla->nla_len = nla_attr_size(attrlen);
436 
437 	memset((unsigned char *) nla + nla->nla_len, 0, nla_padlen(attrlen));
438 
439 	return nla;
440 }
441 EXPORT_SYMBOL(__nla_reserve);
442 
443 /**
444  * __nla_reserve_64bit - reserve room for attribute on the skb and align it
445  * @skb: socket buffer to reserve room on
446  * @attrtype: attribute type
447  * @attrlen: length of attribute payload
448  * @padattr: attribute type for the padding
449  *
450  * Adds a netlink attribute header to a socket buffer and reserves
451  * room for the payload but does not copy it. It also ensure that this
452  * attribute will have a 64-bit aligned nla_data() area.
453  *
454  * The caller is responsible to ensure that the skb provides enough
455  * tailroom for the attribute header and payload.
456  */
457 struct nlattr *__nla_reserve_64bit(struct sk_buff *skb, int attrtype,
458 				   int attrlen, int padattr)
459 {
460 	if (nla_need_padding_for_64bit(skb))
461 		nla_align_64bit(skb, padattr);
462 
463 	return __nla_reserve(skb, attrtype, attrlen);
464 }
465 EXPORT_SYMBOL(__nla_reserve_64bit);
466 
467 /**
468  * __nla_reserve_nohdr - reserve room for attribute without header
469  * @skb: socket buffer to reserve room on
470  * @attrlen: length of attribute payload
471  *
472  * Reserves room for attribute payload without a header.
473  *
474  * The caller is responsible to ensure that the skb provides enough
475  * tailroom for the payload.
476  */
477 void *__nla_reserve_nohdr(struct sk_buff *skb, int attrlen)
478 {
479 	return skb_put_zero(skb, NLA_ALIGN(attrlen));
480 }
481 EXPORT_SYMBOL(__nla_reserve_nohdr);
482 
483 /**
484  * nla_reserve - reserve room for attribute on the skb
485  * @skb: socket buffer to reserve room on
486  * @attrtype: attribute type
487  * @attrlen: length of attribute payload
488  *
489  * Adds a netlink attribute header to a socket buffer and reserves
490  * room for the payload but does not copy it.
491  *
492  * Returns NULL if the tailroom of the skb is insufficient to store
493  * the attribute header and payload.
494  */
495 struct nlattr *nla_reserve(struct sk_buff *skb, int attrtype, int attrlen)
496 {
497 	if (unlikely(skb_tailroom(skb) < nla_total_size(attrlen)))
498 		return NULL;
499 
500 	return __nla_reserve(skb, attrtype, attrlen);
501 }
502 EXPORT_SYMBOL(nla_reserve);
503 
504 /**
505  * nla_reserve_64bit - reserve room for attribute on the skb and align it
506  * @skb: socket buffer to reserve room on
507  * @attrtype: attribute type
508  * @attrlen: length of attribute payload
509  * @padattr: attribute type for the padding
510  *
511  * Adds a netlink attribute header to a socket buffer and reserves
512  * room for the payload but does not copy it. It also ensure that this
513  * attribute will have a 64-bit aligned nla_data() area.
514  *
515  * Returns NULL if the tailroom of the skb is insufficient to store
516  * the attribute header and payload.
517  */
518 struct nlattr *nla_reserve_64bit(struct sk_buff *skb, int attrtype, int attrlen,
519 				 int padattr)
520 {
521 	size_t len;
522 
523 	if (nla_need_padding_for_64bit(skb))
524 		len = nla_total_size_64bit(attrlen);
525 	else
526 		len = nla_total_size(attrlen);
527 	if (unlikely(skb_tailroom(skb) < len))
528 		return NULL;
529 
530 	return __nla_reserve_64bit(skb, attrtype, attrlen, padattr);
531 }
532 EXPORT_SYMBOL(nla_reserve_64bit);
533 
534 /**
535  * nla_reserve_nohdr - reserve room for attribute without header
536  * @skb: socket buffer to reserve room on
537  * @attrlen: length of attribute payload
538  *
539  * Reserves room for attribute payload without a header.
540  *
541  * Returns NULL if the tailroom of the skb is insufficient to store
542  * the attribute payload.
543  */
544 void *nla_reserve_nohdr(struct sk_buff *skb, int attrlen)
545 {
546 	if (unlikely(skb_tailroom(skb) < NLA_ALIGN(attrlen)))
547 		return NULL;
548 
549 	return __nla_reserve_nohdr(skb, attrlen);
550 }
551 EXPORT_SYMBOL(nla_reserve_nohdr);
552 
553 /**
554  * __nla_put - Add a netlink attribute to a socket buffer
555  * @skb: socket buffer to add attribute to
556  * @attrtype: attribute type
557  * @attrlen: length of attribute payload
558  * @data: head of attribute payload
559  *
560  * The caller is responsible to ensure that the skb provides enough
561  * tailroom for the attribute header and payload.
562  */
563 void __nla_put(struct sk_buff *skb, int attrtype, int attrlen,
564 			     const void *data)
565 {
566 	struct nlattr *nla;
567 
568 	nla = __nla_reserve(skb, attrtype, attrlen);
569 	memcpy(nla_data(nla), data, attrlen);
570 }
571 EXPORT_SYMBOL(__nla_put);
572 
573 /**
574  * __nla_put_64bit - Add a netlink attribute to a socket buffer and align it
575  * @skb: socket buffer to add attribute to
576  * @attrtype: attribute type
577  * @attrlen: length of attribute payload
578  * @data: head of attribute payload
579  * @padattr: attribute type for the padding
580  *
581  * The caller is responsible to ensure that the skb provides enough
582  * tailroom for the attribute header and payload.
583  */
584 void __nla_put_64bit(struct sk_buff *skb, int attrtype, int attrlen,
585 		     const void *data, int padattr)
586 {
587 	struct nlattr *nla;
588 
589 	nla = __nla_reserve_64bit(skb, attrtype, attrlen, padattr);
590 	memcpy(nla_data(nla), data, attrlen);
591 }
592 EXPORT_SYMBOL(__nla_put_64bit);
593 
594 /**
595  * __nla_put_nohdr - Add a netlink attribute without header
596  * @skb: socket buffer to add attribute to
597  * @attrlen: length of attribute payload
598  * @data: head of attribute payload
599  *
600  * The caller is responsible to ensure that the skb provides enough
601  * tailroom for the attribute payload.
602  */
603 void __nla_put_nohdr(struct sk_buff *skb, int attrlen, const void *data)
604 {
605 	void *start;
606 
607 	start = __nla_reserve_nohdr(skb, attrlen);
608 	memcpy(start, data, attrlen);
609 }
610 EXPORT_SYMBOL(__nla_put_nohdr);
611 
612 /**
613  * nla_put - Add a netlink attribute to a socket buffer
614  * @skb: socket buffer to add attribute to
615  * @attrtype: attribute type
616  * @attrlen: length of attribute payload
617  * @data: head of attribute payload
618  *
619  * Returns -EMSGSIZE if the tailroom of the skb is insufficient to store
620  * the attribute header and payload.
621  */
622 int nla_put(struct sk_buff *skb, int attrtype, int attrlen, const void *data)
623 {
624 	if (unlikely(skb_tailroom(skb) < nla_total_size(attrlen)))
625 		return -EMSGSIZE;
626 
627 	__nla_put(skb, attrtype, attrlen, data);
628 	return 0;
629 }
630 EXPORT_SYMBOL(nla_put);
631 
632 /**
633  * nla_put_64bit - Add a netlink attribute to a socket buffer and align it
634  * @skb: socket buffer to add attribute to
635  * @attrtype: attribute type
636  * @attrlen: length of attribute payload
637  * @data: head of attribute payload
638  * @padattr: attribute type for the padding
639  *
640  * Returns -EMSGSIZE if the tailroom of the skb is insufficient to store
641  * the attribute header and payload.
642  */
643 int nla_put_64bit(struct sk_buff *skb, int attrtype, int attrlen,
644 		  const void *data, int padattr)
645 {
646 	size_t len;
647 
648 	if (nla_need_padding_for_64bit(skb))
649 		len = nla_total_size_64bit(attrlen);
650 	else
651 		len = nla_total_size(attrlen);
652 	if (unlikely(skb_tailroom(skb) < len))
653 		return -EMSGSIZE;
654 
655 	__nla_put_64bit(skb, attrtype, attrlen, data, padattr);
656 	return 0;
657 }
658 EXPORT_SYMBOL(nla_put_64bit);
659 
660 /**
661  * nla_put_nohdr - Add a netlink attribute without header
662  * @skb: socket buffer to add attribute to
663  * @attrlen: length of attribute payload
664  * @data: head of attribute payload
665  *
666  * Returns -EMSGSIZE if the tailroom of the skb is insufficient to store
667  * the attribute payload.
668  */
669 int nla_put_nohdr(struct sk_buff *skb, int attrlen, const void *data)
670 {
671 	if (unlikely(skb_tailroom(skb) < NLA_ALIGN(attrlen)))
672 		return -EMSGSIZE;
673 
674 	__nla_put_nohdr(skb, attrlen, data);
675 	return 0;
676 }
677 EXPORT_SYMBOL(nla_put_nohdr);
678 
679 /**
680  * nla_append - Add a netlink attribute without header or padding
681  * @skb: socket buffer to add attribute to
682  * @attrlen: length of attribute payload
683  * @data: head of attribute payload
684  *
685  * Returns -EMSGSIZE if the tailroom of the skb is insufficient to store
686  * the attribute payload.
687  */
688 int nla_append(struct sk_buff *skb, int attrlen, const void *data)
689 {
690 	if (unlikely(skb_tailroom(skb) < NLA_ALIGN(attrlen)))
691 		return -EMSGSIZE;
692 
693 	skb_put_data(skb, data, attrlen);
694 	return 0;
695 }
696 EXPORT_SYMBOL(nla_append);
697 #endif
698