xref: /openbmc/linux/net/ipv4/cipso_ipv4.c (revision 710b797c)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * CIPSO - Commercial IP Security Option
4  *
5  * This is an implementation of the CIPSO 2.2 protocol as specified in
6  * draft-ietf-cipso-ipsecurity-01.txt with additional tag types as found in
7  * FIPS-188.  While CIPSO never became a full IETF RFC standard many vendors
8  * have chosen to adopt the protocol and over the years it has become a
9  * de-facto standard for labeled networking.
10  *
11  * The CIPSO draft specification can be found in the kernel's Documentation
12  * directory as well as the following URL:
13  *   https://tools.ietf.org/id/draft-ietf-cipso-ipsecurity-01.txt
14  * The FIPS-188 specification can be found at the following URL:
15  *   https://www.itl.nist.gov/fipspubs/fip188.htm
16  *
17  * Author: Paul Moore <paul.moore@hp.com>
18  */
19 
20 /*
21  * (c) Copyright Hewlett-Packard Development Company, L.P., 2006, 2008
22  */
23 
24 #include <linux/init.h>
25 #include <linux/types.h>
26 #include <linux/rcupdate.h>
27 #include <linux/list.h>
28 #include <linux/spinlock.h>
29 #include <linux/string.h>
30 #include <linux/jhash.h>
31 #include <linux/audit.h>
32 #include <linux/slab.h>
33 #include <net/ip.h>
34 #include <net/icmp.h>
35 #include <net/tcp.h>
36 #include <net/netlabel.h>
37 #include <net/cipso_ipv4.h>
38 #include <linux/atomic.h>
39 #include <linux/bug.h>
40 #include <asm/unaligned.h>
41 
42 /* List of available DOI definitions */
43 /* XXX - This currently assumes a minimal number of different DOIs in use,
44  * if in practice there are a lot of different DOIs this list should
45  * probably be turned into a hash table or something similar so we
46  * can do quick lookups. */
47 static DEFINE_SPINLOCK(cipso_v4_doi_list_lock);
48 static LIST_HEAD(cipso_v4_doi_list);
49 
50 /* Label mapping cache */
51 int cipso_v4_cache_enabled = 1;
52 int cipso_v4_cache_bucketsize = 10;
53 #define CIPSO_V4_CACHE_BUCKETBITS     7
54 #define CIPSO_V4_CACHE_BUCKETS        (1 << CIPSO_V4_CACHE_BUCKETBITS)
55 #define CIPSO_V4_CACHE_REORDERLIMIT   10
56 struct cipso_v4_map_cache_bkt {
57 	spinlock_t lock;
58 	u32 size;
59 	struct list_head list;
60 };
61 
62 struct cipso_v4_map_cache_entry {
63 	u32 hash;
64 	unsigned char *key;
65 	size_t key_len;
66 
67 	struct netlbl_lsm_cache *lsm_data;
68 
69 	u32 activity;
70 	struct list_head list;
71 };
72 
73 static struct cipso_v4_map_cache_bkt *cipso_v4_cache;
74 
75 /* Restricted bitmap (tag #1) flags */
76 int cipso_v4_rbm_optfmt = 0;
77 int cipso_v4_rbm_strictvalid = 1;
78 
79 /*
80  * Protocol Constants
81  */
82 
83 /* Maximum size of the CIPSO IP option, derived from the fact that the maximum
84  * IPv4 header size is 60 bytes and the base IPv4 header is 20 bytes long. */
85 #define CIPSO_V4_OPT_LEN_MAX          40
86 
87 /* Length of the base CIPSO option, this includes the option type (1 byte), the
88  * option length (1 byte), and the DOI (4 bytes). */
89 #define CIPSO_V4_HDR_LEN              6
90 
91 /* Base length of the restrictive category bitmap tag (tag #1). */
92 #define CIPSO_V4_TAG_RBM_BLEN         4
93 
94 /* Base length of the enumerated category tag (tag #2). */
95 #define CIPSO_V4_TAG_ENUM_BLEN        4
96 
97 /* Base length of the ranged categories bitmap tag (tag #5). */
98 #define CIPSO_V4_TAG_RNG_BLEN         4
99 /* The maximum number of category ranges permitted in the ranged category tag
100  * (tag #5).  You may note that the IETF draft states that the maximum number
101  * of category ranges is 7, but if the low end of the last category range is
102  * zero then it is possible to fit 8 category ranges because the zero should
103  * be omitted. */
104 #define CIPSO_V4_TAG_RNG_CAT_MAX      8
105 
106 /* Base length of the local tag (non-standard tag).
107  *  Tag definition (may change between kernel versions)
108  *
109  * 0          8          16         24         32
110  * +----------+----------+----------+----------+
111  * | 10000000 | 00000110 | 32-bit secid value  |
112  * +----------+----------+----------+----------+
113  * | in (host byte order)|
114  * +----------+----------+
115  *
116  */
117 #define CIPSO_V4_TAG_LOC_BLEN         6
118 
119 /*
120  * Helper Functions
121  */
122 
123 /**
124  * cipso_v4_cache_entry_free - Frees a cache entry
125  * @entry: the entry to free
126  *
127  * Description:
128  * This function frees the memory associated with a cache entry including the
129  * LSM cache data if there are no longer any users, i.e. reference count == 0.
130  *
131  */
132 static void cipso_v4_cache_entry_free(struct cipso_v4_map_cache_entry *entry)
133 {
134 	if (entry->lsm_data)
135 		netlbl_secattr_cache_free(entry->lsm_data);
136 	kfree(entry->key);
137 	kfree(entry);
138 }
139 
140 /**
141  * cipso_v4_map_cache_hash - Hashing function for the CIPSO cache
142  * @key: the hash key
143  * @key_len: the length of the key in bytes
144  *
145  * Description:
146  * The CIPSO tag hashing function.  Returns a 32-bit hash value.
147  *
148  */
149 static u32 cipso_v4_map_cache_hash(const unsigned char *key, u32 key_len)
150 {
151 	return jhash(key, key_len, 0);
152 }
153 
154 /*
155  * Label Mapping Cache Functions
156  */
157 
158 /**
159  * cipso_v4_cache_init - Initialize the CIPSO cache
160  *
161  * Description:
162  * Initializes the CIPSO label mapping cache, this function should be called
163  * before any of the other functions defined in this file.  Returns zero on
164  * success, negative values on error.
165  *
166  */
167 static int __init cipso_v4_cache_init(void)
168 {
169 	u32 iter;
170 
171 	cipso_v4_cache = kcalloc(CIPSO_V4_CACHE_BUCKETS,
172 				 sizeof(struct cipso_v4_map_cache_bkt),
173 				 GFP_KERNEL);
174 	if (!cipso_v4_cache)
175 		return -ENOMEM;
176 
177 	for (iter = 0; iter < CIPSO_V4_CACHE_BUCKETS; iter++) {
178 		spin_lock_init(&cipso_v4_cache[iter].lock);
179 		cipso_v4_cache[iter].size = 0;
180 		INIT_LIST_HEAD(&cipso_v4_cache[iter].list);
181 	}
182 
183 	return 0;
184 }
185 
186 /**
187  * cipso_v4_cache_invalidate - Invalidates the current CIPSO cache
188  *
189  * Description:
190  * Invalidates and frees any entries in the CIPSO cache.
191  *
192  */
193 void cipso_v4_cache_invalidate(void)
194 {
195 	struct cipso_v4_map_cache_entry *entry, *tmp_entry;
196 	u32 iter;
197 
198 	for (iter = 0; iter < CIPSO_V4_CACHE_BUCKETS; iter++) {
199 		spin_lock_bh(&cipso_v4_cache[iter].lock);
200 		list_for_each_entry_safe(entry,
201 					 tmp_entry,
202 					 &cipso_v4_cache[iter].list, list) {
203 			list_del(&entry->list);
204 			cipso_v4_cache_entry_free(entry);
205 		}
206 		cipso_v4_cache[iter].size = 0;
207 		spin_unlock_bh(&cipso_v4_cache[iter].lock);
208 	}
209 }
210 
211 /**
212  * cipso_v4_cache_check - Check the CIPSO cache for a label mapping
213  * @key: the buffer to check
214  * @key_len: buffer length in bytes
215  * @secattr: the security attribute struct to use
216  *
217  * Description:
218  * This function checks the cache to see if a label mapping already exists for
219  * the given key.  If there is a match then the cache is adjusted and the
220  * @secattr struct is populated with the correct LSM security attributes.  The
221  * cache is adjusted in the following manner if the entry is not already the
222  * first in the cache bucket:
223  *
224  *  1. The cache entry's activity counter is incremented
225  *  2. The previous (higher ranking) entry's activity counter is decremented
226  *  3. If the difference between the two activity counters is geater than
227  *     CIPSO_V4_CACHE_REORDERLIMIT the two entries are swapped
228  *
229  * Returns zero on success, -ENOENT for a cache miss, and other negative values
230  * on error.
231  *
232  */
233 static int cipso_v4_cache_check(const unsigned char *key,
234 				u32 key_len,
235 				struct netlbl_lsm_secattr *secattr)
236 {
237 	u32 bkt;
238 	struct cipso_v4_map_cache_entry *entry;
239 	struct cipso_v4_map_cache_entry *prev_entry = NULL;
240 	u32 hash;
241 
242 	if (!cipso_v4_cache_enabled)
243 		return -ENOENT;
244 
245 	hash = cipso_v4_map_cache_hash(key, key_len);
246 	bkt = hash & (CIPSO_V4_CACHE_BUCKETS - 1);
247 	spin_lock_bh(&cipso_v4_cache[bkt].lock);
248 	list_for_each_entry(entry, &cipso_v4_cache[bkt].list, list) {
249 		if (entry->hash == hash &&
250 		    entry->key_len == key_len &&
251 		    memcmp(entry->key, key, key_len) == 0) {
252 			entry->activity += 1;
253 			refcount_inc(&entry->lsm_data->refcount);
254 			secattr->cache = entry->lsm_data;
255 			secattr->flags |= NETLBL_SECATTR_CACHE;
256 			secattr->type = NETLBL_NLTYPE_CIPSOV4;
257 			if (!prev_entry) {
258 				spin_unlock_bh(&cipso_v4_cache[bkt].lock);
259 				return 0;
260 			}
261 
262 			if (prev_entry->activity > 0)
263 				prev_entry->activity -= 1;
264 			if (entry->activity > prev_entry->activity &&
265 			    entry->activity - prev_entry->activity >
266 			    CIPSO_V4_CACHE_REORDERLIMIT) {
267 				__list_del(entry->list.prev, entry->list.next);
268 				__list_add(&entry->list,
269 					   prev_entry->list.prev,
270 					   &prev_entry->list);
271 			}
272 
273 			spin_unlock_bh(&cipso_v4_cache[bkt].lock);
274 			return 0;
275 		}
276 		prev_entry = entry;
277 	}
278 	spin_unlock_bh(&cipso_v4_cache[bkt].lock);
279 
280 	return -ENOENT;
281 }
282 
283 /**
284  * cipso_v4_cache_add - Add an entry to the CIPSO cache
285  * @cipso_ptr: pointer to CIPSO IP option
286  * @secattr: the packet's security attributes
287  *
288  * Description:
289  * Add a new entry into the CIPSO label mapping cache.  Add the new entry to
290  * head of the cache bucket's list, if the cache bucket is out of room remove
291  * the last entry in the list first.  It is important to note that there is
292  * currently no checking for duplicate keys.  Returns zero on success,
293  * negative values on failure.
294  *
295  */
296 int cipso_v4_cache_add(const unsigned char *cipso_ptr,
297 		       const struct netlbl_lsm_secattr *secattr)
298 {
299 	int ret_val = -EPERM;
300 	u32 bkt;
301 	struct cipso_v4_map_cache_entry *entry = NULL;
302 	struct cipso_v4_map_cache_entry *old_entry = NULL;
303 	u32 cipso_ptr_len;
304 
305 	if (!cipso_v4_cache_enabled || cipso_v4_cache_bucketsize <= 0)
306 		return 0;
307 
308 	cipso_ptr_len = cipso_ptr[1];
309 
310 	entry = kzalloc(sizeof(*entry), GFP_ATOMIC);
311 	if (!entry)
312 		return -ENOMEM;
313 	entry->key = kmemdup(cipso_ptr, cipso_ptr_len, GFP_ATOMIC);
314 	if (!entry->key) {
315 		ret_val = -ENOMEM;
316 		goto cache_add_failure;
317 	}
318 	entry->key_len = cipso_ptr_len;
319 	entry->hash = cipso_v4_map_cache_hash(cipso_ptr, cipso_ptr_len);
320 	refcount_inc(&secattr->cache->refcount);
321 	entry->lsm_data = secattr->cache;
322 
323 	bkt = entry->hash & (CIPSO_V4_CACHE_BUCKETS - 1);
324 	spin_lock_bh(&cipso_v4_cache[bkt].lock);
325 	if (cipso_v4_cache[bkt].size < cipso_v4_cache_bucketsize) {
326 		list_add(&entry->list, &cipso_v4_cache[bkt].list);
327 		cipso_v4_cache[bkt].size += 1;
328 	} else {
329 		old_entry = list_entry(cipso_v4_cache[bkt].list.prev,
330 				       struct cipso_v4_map_cache_entry, list);
331 		list_del(&old_entry->list);
332 		list_add(&entry->list, &cipso_v4_cache[bkt].list);
333 		cipso_v4_cache_entry_free(old_entry);
334 	}
335 	spin_unlock_bh(&cipso_v4_cache[bkt].lock);
336 
337 	return 0;
338 
339 cache_add_failure:
340 	if (entry)
341 		cipso_v4_cache_entry_free(entry);
342 	return ret_val;
343 }
344 
345 /*
346  * DOI List Functions
347  */
348 
349 /**
350  * cipso_v4_doi_search - Searches for a DOI definition
351  * @doi: the DOI to search for
352  *
353  * Description:
354  * Search the DOI definition list for a DOI definition with a DOI value that
355  * matches @doi.  The caller is responsible for calling rcu_read_[un]lock().
356  * Returns a pointer to the DOI definition on success and NULL on failure.
357  */
358 static struct cipso_v4_doi *cipso_v4_doi_search(u32 doi)
359 {
360 	struct cipso_v4_doi *iter;
361 
362 	list_for_each_entry_rcu(iter, &cipso_v4_doi_list, list)
363 		if (iter->doi == doi && refcount_read(&iter->refcount))
364 			return iter;
365 	return NULL;
366 }
367 
368 /**
369  * cipso_v4_doi_add - Add a new DOI to the CIPSO protocol engine
370  * @doi_def: the DOI structure
371  * @audit_info: NetLabel audit information
372  *
373  * Description:
374  * The caller defines a new DOI for use by the CIPSO engine and calls this
375  * function to add it to the list of acceptable domains.  The caller must
376  * ensure that the mapping table specified in @doi_def->map meets all of the
377  * requirements of the mapping type (see cipso_ipv4.h for details).  Returns
378  * zero on success and non-zero on failure.
379  *
380  */
381 int cipso_v4_doi_add(struct cipso_v4_doi *doi_def,
382 		     struct netlbl_audit *audit_info)
383 {
384 	int ret_val = -EINVAL;
385 	u32 iter;
386 	u32 doi;
387 	u32 doi_type;
388 	struct audit_buffer *audit_buf;
389 
390 	doi = doi_def->doi;
391 	doi_type = doi_def->type;
392 
393 	if (doi_def->doi == CIPSO_V4_DOI_UNKNOWN)
394 		goto doi_add_return;
395 	for (iter = 0; iter < CIPSO_V4_TAG_MAXCNT; iter++) {
396 		switch (doi_def->tags[iter]) {
397 		case CIPSO_V4_TAG_RBITMAP:
398 			break;
399 		case CIPSO_V4_TAG_RANGE:
400 		case CIPSO_V4_TAG_ENUM:
401 			if (doi_def->type != CIPSO_V4_MAP_PASS)
402 				goto doi_add_return;
403 			break;
404 		case CIPSO_V4_TAG_LOCAL:
405 			if (doi_def->type != CIPSO_V4_MAP_LOCAL)
406 				goto doi_add_return;
407 			break;
408 		case CIPSO_V4_TAG_INVALID:
409 			if (iter == 0)
410 				goto doi_add_return;
411 			break;
412 		default:
413 			goto doi_add_return;
414 		}
415 	}
416 
417 	refcount_set(&doi_def->refcount, 1);
418 
419 	spin_lock(&cipso_v4_doi_list_lock);
420 	if (cipso_v4_doi_search(doi_def->doi)) {
421 		spin_unlock(&cipso_v4_doi_list_lock);
422 		ret_val = -EEXIST;
423 		goto doi_add_return;
424 	}
425 	list_add_tail_rcu(&doi_def->list, &cipso_v4_doi_list);
426 	spin_unlock(&cipso_v4_doi_list_lock);
427 	ret_val = 0;
428 
429 doi_add_return:
430 	audit_buf = netlbl_audit_start(AUDIT_MAC_CIPSOV4_ADD, audit_info);
431 	if (audit_buf) {
432 		const char *type_str;
433 		switch (doi_type) {
434 		case CIPSO_V4_MAP_TRANS:
435 			type_str = "trans";
436 			break;
437 		case CIPSO_V4_MAP_PASS:
438 			type_str = "pass";
439 			break;
440 		case CIPSO_V4_MAP_LOCAL:
441 			type_str = "local";
442 			break;
443 		default:
444 			type_str = "(unknown)";
445 		}
446 		audit_log_format(audit_buf,
447 				 " cipso_doi=%u cipso_type=%s res=%u",
448 				 doi, type_str, ret_val == 0 ? 1 : 0);
449 		audit_log_end(audit_buf);
450 	}
451 
452 	return ret_val;
453 }
454 
455 /**
456  * cipso_v4_doi_free - Frees a DOI definition
457  * @doi_def: the DOI definition
458  *
459  * Description:
460  * This function frees all of the memory associated with a DOI definition.
461  *
462  */
463 void cipso_v4_doi_free(struct cipso_v4_doi *doi_def)
464 {
465 	if (!doi_def)
466 		return;
467 
468 	switch (doi_def->type) {
469 	case CIPSO_V4_MAP_TRANS:
470 		kfree(doi_def->map.std->lvl.cipso);
471 		kfree(doi_def->map.std->lvl.local);
472 		kfree(doi_def->map.std->cat.cipso);
473 		kfree(doi_def->map.std->cat.local);
474 		break;
475 	}
476 	kfree(doi_def);
477 }
478 
479 /**
480  * cipso_v4_doi_free_rcu - Frees a DOI definition via the RCU pointer
481  * @entry: the entry's RCU field
482  *
483  * Description:
484  * This function is designed to be used as a callback to the call_rcu()
485  * function so that the memory allocated to the DOI definition can be released
486  * safely.
487  *
488  */
489 static void cipso_v4_doi_free_rcu(struct rcu_head *entry)
490 {
491 	struct cipso_v4_doi *doi_def;
492 
493 	doi_def = container_of(entry, struct cipso_v4_doi, rcu);
494 	cipso_v4_doi_free(doi_def);
495 }
496 
497 /**
498  * cipso_v4_doi_remove - Remove an existing DOI from the CIPSO protocol engine
499  * @doi: the DOI value
500  * @audit_info: NetLabel audit information
501  *
502  * Description:
503  * Removes a DOI definition from the CIPSO engine.  The NetLabel routines will
504  * be called to release their own LSM domain mappings as well as our own
505  * domain list.  Returns zero on success and negative values on failure.
506  *
507  */
508 int cipso_v4_doi_remove(u32 doi, struct netlbl_audit *audit_info)
509 {
510 	int ret_val;
511 	struct cipso_v4_doi *doi_def;
512 	struct audit_buffer *audit_buf;
513 
514 	spin_lock(&cipso_v4_doi_list_lock);
515 	doi_def = cipso_v4_doi_search(doi);
516 	if (!doi_def) {
517 		spin_unlock(&cipso_v4_doi_list_lock);
518 		ret_val = -ENOENT;
519 		goto doi_remove_return;
520 	}
521 	list_del_rcu(&doi_def->list);
522 	spin_unlock(&cipso_v4_doi_list_lock);
523 
524 	cipso_v4_doi_putdef(doi_def);
525 	ret_val = 0;
526 
527 doi_remove_return:
528 	audit_buf = netlbl_audit_start(AUDIT_MAC_CIPSOV4_DEL, audit_info);
529 	if (audit_buf) {
530 		audit_log_format(audit_buf,
531 				 " cipso_doi=%u res=%u",
532 				 doi, ret_val == 0 ? 1 : 0);
533 		audit_log_end(audit_buf);
534 	}
535 
536 	return ret_val;
537 }
538 
539 /**
540  * cipso_v4_doi_getdef - Returns a reference to a valid DOI definition
541  * @doi: the DOI value
542  *
543  * Description:
544  * Searches for a valid DOI definition and if one is found it is returned to
545  * the caller.  Otherwise NULL is returned.  The caller must ensure that
546  * rcu_read_lock() is held while accessing the returned definition and the DOI
547  * definition reference count is decremented when the caller is done.
548  *
549  */
550 struct cipso_v4_doi *cipso_v4_doi_getdef(u32 doi)
551 {
552 	struct cipso_v4_doi *doi_def;
553 
554 	rcu_read_lock();
555 	doi_def = cipso_v4_doi_search(doi);
556 	if (!doi_def)
557 		goto doi_getdef_return;
558 	if (!refcount_inc_not_zero(&doi_def->refcount))
559 		doi_def = NULL;
560 
561 doi_getdef_return:
562 	rcu_read_unlock();
563 	return doi_def;
564 }
565 
566 /**
567  * cipso_v4_doi_putdef - Releases a reference for the given DOI definition
568  * @doi_def: the DOI definition
569  *
570  * Description:
571  * Releases a DOI definition reference obtained from cipso_v4_doi_getdef().
572  *
573  */
574 void cipso_v4_doi_putdef(struct cipso_v4_doi *doi_def)
575 {
576 	if (!doi_def)
577 		return;
578 
579 	if (!refcount_dec_and_test(&doi_def->refcount))
580 		return;
581 
582 	cipso_v4_cache_invalidate();
583 	call_rcu(&doi_def->rcu, cipso_v4_doi_free_rcu);
584 }
585 
586 /**
587  * cipso_v4_doi_walk - Iterate through the DOI definitions
588  * @skip_cnt: skip past this number of DOI definitions, updated
589  * @callback: callback for each DOI definition
590  * @cb_arg: argument for the callback function
591  *
592  * Description:
593  * Iterate over the DOI definition list, skipping the first @skip_cnt entries.
594  * For each entry call @callback, if @callback returns a negative value stop
595  * 'walking' through the list and return.  Updates the value in @skip_cnt upon
596  * return.  Returns zero on success, negative values on failure.
597  *
598  */
599 int cipso_v4_doi_walk(u32 *skip_cnt,
600 		     int (*callback) (struct cipso_v4_doi *doi_def, void *arg),
601 		     void *cb_arg)
602 {
603 	int ret_val = -ENOENT;
604 	u32 doi_cnt = 0;
605 	struct cipso_v4_doi *iter_doi;
606 
607 	rcu_read_lock();
608 	list_for_each_entry_rcu(iter_doi, &cipso_v4_doi_list, list)
609 		if (refcount_read(&iter_doi->refcount) > 0) {
610 			if (doi_cnt++ < *skip_cnt)
611 				continue;
612 			ret_val = callback(iter_doi, cb_arg);
613 			if (ret_val < 0) {
614 				doi_cnt--;
615 				goto doi_walk_return;
616 			}
617 		}
618 
619 doi_walk_return:
620 	rcu_read_unlock();
621 	*skip_cnt = doi_cnt;
622 	return ret_val;
623 }
624 
625 /*
626  * Label Mapping Functions
627  */
628 
629 /**
630  * cipso_v4_map_lvl_valid - Checks to see if the given level is understood
631  * @doi_def: the DOI definition
632  * @level: the level to check
633  *
634  * Description:
635  * Checks the given level against the given DOI definition and returns a
636  * negative value if the level does not have a valid mapping and a zero value
637  * if the level is defined by the DOI.
638  *
639  */
640 static int cipso_v4_map_lvl_valid(const struct cipso_v4_doi *doi_def, u8 level)
641 {
642 	switch (doi_def->type) {
643 	case CIPSO_V4_MAP_PASS:
644 		return 0;
645 	case CIPSO_V4_MAP_TRANS:
646 		if ((level < doi_def->map.std->lvl.cipso_size) &&
647 		    (doi_def->map.std->lvl.cipso[level] < CIPSO_V4_INV_LVL))
648 			return 0;
649 		break;
650 	}
651 
652 	return -EFAULT;
653 }
654 
655 /**
656  * cipso_v4_map_lvl_hton - Perform a level mapping from the host to the network
657  * @doi_def: the DOI definition
658  * @host_lvl: the host MLS level
659  * @net_lvl: the network/CIPSO MLS level
660  *
661  * Description:
662  * Perform a label mapping to translate a local MLS level to the correct
663  * CIPSO level using the given DOI definition.  Returns zero on success,
664  * negative values otherwise.
665  *
666  */
667 static int cipso_v4_map_lvl_hton(const struct cipso_v4_doi *doi_def,
668 				 u32 host_lvl,
669 				 u32 *net_lvl)
670 {
671 	switch (doi_def->type) {
672 	case CIPSO_V4_MAP_PASS:
673 		*net_lvl = host_lvl;
674 		return 0;
675 	case CIPSO_V4_MAP_TRANS:
676 		if (host_lvl < doi_def->map.std->lvl.local_size &&
677 		    doi_def->map.std->lvl.local[host_lvl] < CIPSO_V4_INV_LVL) {
678 			*net_lvl = doi_def->map.std->lvl.local[host_lvl];
679 			return 0;
680 		}
681 		return -EPERM;
682 	}
683 
684 	return -EINVAL;
685 }
686 
687 /**
688  * cipso_v4_map_lvl_ntoh - Perform a level mapping from the network to the host
689  * @doi_def: the DOI definition
690  * @net_lvl: the network/CIPSO MLS level
691  * @host_lvl: the host MLS level
692  *
693  * Description:
694  * Perform a label mapping to translate a CIPSO level to the correct local MLS
695  * level using the given DOI definition.  Returns zero on success, negative
696  * values otherwise.
697  *
698  */
699 static int cipso_v4_map_lvl_ntoh(const struct cipso_v4_doi *doi_def,
700 				 u32 net_lvl,
701 				 u32 *host_lvl)
702 {
703 	struct cipso_v4_std_map_tbl *map_tbl;
704 
705 	switch (doi_def->type) {
706 	case CIPSO_V4_MAP_PASS:
707 		*host_lvl = net_lvl;
708 		return 0;
709 	case CIPSO_V4_MAP_TRANS:
710 		map_tbl = doi_def->map.std;
711 		if (net_lvl < map_tbl->lvl.cipso_size &&
712 		    map_tbl->lvl.cipso[net_lvl] < CIPSO_V4_INV_LVL) {
713 			*host_lvl = doi_def->map.std->lvl.cipso[net_lvl];
714 			return 0;
715 		}
716 		return -EPERM;
717 	}
718 
719 	return -EINVAL;
720 }
721 
722 /**
723  * cipso_v4_map_cat_rbm_valid - Checks to see if the category bitmap is valid
724  * @doi_def: the DOI definition
725  * @bitmap: category bitmap
726  * @bitmap_len: bitmap length in bytes
727  *
728  * Description:
729  * Checks the given category bitmap against the given DOI definition and
730  * returns a negative value if any of the categories in the bitmap do not have
731  * a valid mapping and a zero value if all of the categories are valid.
732  *
733  */
734 static int cipso_v4_map_cat_rbm_valid(const struct cipso_v4_doi *doi_def,
735 				      const unsigned char *bitmap,
736 				      u32 bitmap_len)
737 {
738 	int cat = -1;
739 	u32 bitmap_len_bits = bitmap_len * 8;
740 	u32 cipso_cat_size;
741 	u32 *cipso_array;
742 
743 	switch (doi_def->type) {
744 	case CIPSO_V4_MAP_PASS:
745 		return 0;
746 	case CIPSO_V4_MAP_TRANS:
747 		cipso_cat_size = doi_def->map.std->cat.cipso_size;
748 		cipso_array = doi_def->map.std->cat.cipso;
749 		for (;;) {
750 			cat = netlbl_bitmap_walk(bitmap,
751 						 bitmap_len_bits,
752 						 cat + 1,
753 						 1);
754 			if (cat < 0)
755 				break;
756 			if (cat >= cipso_cat_size ||
757 			    cipso_array[cat] >= CIPSO_V4_INV_CAT)
758 				return -EFAULT;
759 		}
760 
761 		if (cat == -1)
762 			return 0;
763 		break;
764 	}
765 
766 	return -EFAULT;
767 }
768 
769 /**
770  * cipso_v4_map_cat_rbm_hton - Perform a category mapping from host to network
771  * @doi_def: the DOI definition
772  * @secattr: the security attributes
773  * @net_cat: the zero'd out category bitmap in network/CIPSO format
774  * @net_cat_len: the length of the CIPSO bitmap in bytes
775  *
776  * Description:
777  * Perform a label mapping to translate a local MLS category bitmap to the
778  * correct CIPSO bitmap using the given DOI definition.  Returns the minimum
779  * size in bytes of the network bitmap on success, negative values otherwise.
780  *
781  */
782 static int cipso_v4_map_cat_rbm_hton(const struct cipso_v4_doi *doi_def,
783 				     const struct netlbl_lsm_secattr *secattr,
784 				     unsigned char *net_cat,
785 				     u32 net_cat_len)
786 {
787 	int host_spot = -1;
788 	u32 net_spot = CIPSO_V4_INV_CAT;
789 	u32 net_spot_max = 0;
790 	u32 net_clen_bits = net_cat_len * 8;
791 	u32 host_cat_size = 0;
792 	u32 *host_cat_array = NULL;
793 
794 	if (doi_def->type == CIPSO_V4_MAP_TRANS) {
795 		host_cat_size = doi_def->map.std->cat.local_size;
796 		host_cat_array = doi_def->map.std->cat.local;
797 	}
798 
799 	for (;;) {
800 		host_spot = netlbl_catmap_walk(secattr->attr.mls.cat,
801 					       host_spot + 1);
802 		if (host_spot < 0)
803 			break;
804 
805 		switch (doi_def->type) {
806 		case CIPSO_V4_MAP_PASS:
807 			net_spot = host_spot;
808 			break;
809 		case CIPSO_V4_MAP_TRANS:
810 			if (host_spot >= host_cat_size)
811 				return -EPERM;
812 			net_spot = host_cat_array[host_spot];
813 			if (net_spot >= CIPSO_V4_INV_CAT)
814 				return -EPERM;
815 			break;
816 		}
817 		if (net_spot >= net_clen_bits)
818 			return -ENOSPC;
819 		netlbl_bitmap_setbit(net_cat, net_spot, 1);
820 
821 		if (net_spot > net_spot_max)
822 			net_spot_max = net_spot;
823 	}
824 
825 	if (++net_spot_max % 8)
826 		return net_spot_max / 8 + 1;
827 	return net_spot_max / 8;
828 }
829 
830 /**
831  * cipso_v4_map_cat_rbm_ntoh - Perform a category mapping from network to host
832  * @doi_def: the DOI definition
833  * @net_cat: the category bitmap in network/CIPSO format
834  * @net_cat_len: the length of the CIPSO bitmap in bytes
835  * @secattr: the security attributes
836  *
837  * Description:
838  * Perform a label mapping to translate a CIPSO bitmap to the correct local
839  * MLS category bitmap using the given DOI definition.  Returns zero on
840  * success, negative values on failure.
841  *
842  */
843 static int cipso_v4_map_cat_rbm_ntoh(const struct cipso_v4_doi *doi_def,
844 				     const unsigned char *net_cat,
845 				     u32 net_cat_len,
846 				     struct netlbl_lsm_secattr *secattr)
847 {
848 	int ret_val;
849 	int net_spot = -1;
850 	u32 host_spot = CIPSO_V4_INV_CAT;
851 	u32 net_clen_bits = net_cat_len * 8;
852 	u32 net_cat_size = 0;
853 	u32 *net_cat_array = NULL;
854 
855 	if (doi_def->type == CIPSO_V4_MAP_TRANS) {
856 		net_cat_size = doi_def->map.std->cat.cipso_size;
857 		net_cat_array = doi_def->map.std->cat.cipso;
858 	}
859 
860 	for (;;) {
861 		net_spot = netlbl_bitmap_walk(net_cat,
862 					      net_clen_bits,
863 					      net_spot + 1,
864 					      1);
865 		if (net_spot < 0) {
866 			if (net_spot == -2)
867 				return -EFAULT;
868 			return 0;
869 		}
870 
871 		switch (doi_def->type) {
872 		case CIPSO_V4_MAP_PASS:
873 			host_spot = net_spot;
874 			break;
875 		case CIPSO_V4_MAP_TRANS:
876 			if (net_spot >= net_cat_size)
877 				return -EPERM;
878 			host_spot = net_cat_array[net_spot];
879 			if (host_spot >= CIPSO_V4_INV_CAT)
880 				return -EPERM;
881 			break;
882 		}
883 		ret_val = netlbl_catmap_setbit(&secattr->attr.mls.cat,
884 						       host_spot,
885 						       GFP_ATOMIC);
886 		if (ret_val != 0)
887 			return ret_val;
888 	}
889 
890 	return -EINVAL;
891 }
892 
893 /**
894  * cipso_v4_map_cat_enum_valid - Checks to see if the categories are valid
895  * @doi_def: the DOI definition
896  * @enumcat: category list
897  * @enumcat_len: length of the category list in bytes
898  *
899  * Description:
900  * Checks the given categories against the given DOI definition and returns a
901  * negative value if any of the categories do not have a valid mapping and a
902  * zero value if all of the categories are valid.
903  *
904  */
905 static int cipso_v4_map_cat_enum_valid(const struct cipso_v4_doi *doi_def,
906 				       const unsigned char *enumcat,
907 				       u32 enumcat_len)
908 {
909 	u16 cat;
910 	int cat_prev = -1;
911 	u32 iter;
912 
913 	if (doi_def->type != CIPSO_V4_MAP_PASS || enumcat_len & 0x01)
914 		return -EFAULT;
915 
916 	for (iter = 0; iter < enumcat_len; iter += 2) {
917 		cat = get_unaligned_be16(&enumcat[iter]);
918 		if (cat <= cat_prev)
919 			return -EFAULT;
920 		cat_prev = cat;
921 	}
922 
923 	return 0;
924 }
925 
926 /**
927  * cipso_v4_map_cat_enum_hton - Perform a category mapping from host to network
928  * @doi_def: the DOI definition
929  * @secattr: the security attributes
930  * @net_cat: the zero'd out category list in network/CIPSO format
931  * @net_cat_len: the length of the CIPSO category list in bytes
932  *
933  * Description:
934  * Perform a label mapping to translate a local MLS category bitmap to the
935  * correct CIPSO category list using the given DOI definition.   Returns the
936  * size in bytes of the network category bitmap on success, negative values
937  * otherwise.
938  *
939  */
940 static int cipso_v4_map_cat_enum_hton(const struct cipso_v4_doi *doi_def,
941 				      const struct netlbl_lsm_secattr *secattr,
942 				      unsigned char *net_cat,
943 				      u32 net_cat_len)
944 {
945 	int cat = -1;
946 	u32 cat_iter = 0;
947 
948 	for (;;) {
949 		cat = netlbl_catmap_walk(secattr->attr.mls.cat, cat + 1);
950 		if (cat < 0)
951 			break;
952 		if ((cat_iter + 2) > net_cat_len)
953 			return -ENOSPC;
954 
955 		*((__be16 *)&net_cat[cat_iter]) = htons(cat);
956 		cat_iter += 2;
957 	}
958 
959 	return cat_iter;
960 }
961 
962 /**
963  * cipso_v4_map_cat_enum_ntoh - Perform a category mapping from network to host
964  * @doi_def: the DOI definition
965  * @net_cat: the category list in network/CIPSO format
966  * @net_cat_len: the length of the CIPSO bitmap in bytes
967  * @secattr: the security attributes
968  *
969  * Description:
970  * Perform a label mapping to translate a CIPSO category list to the correct
971  * local MLS category bitmap using the given DOI definition.  Returns zero on
972  * success, negative values on failure.
973  *
974  */
975 static int cipso_v4_map_cat_enum_ntoh(const struct cipso_v4_doi *doi_def,
976 				      const unsigned char *net_cat,
977 				      u32 net_cat_len,
978 				      struct netlbl_lsm_secattr *secattr)
979 {
980 	int ret_val;
981 	u32 iter;
982 
983 	for (iter = 0; iter < net_cat_len; iter += 2) {
984 		ret_val = netlbl_catmap_setbit(&secattr->attr.mls.cat,
985 					     get_unaligned_be16(&net_cat[iter]),
986 					     GFP_ATOMIC);
987 		if (ret_val != 0)
988 			return ret_val;
989 	}
990 
991 	return 0;
992 }
993 
994 /**
995  * cipso_v4_map_cat_rng_valid - Checks to see if the categories are valid
996  * @doi_def: the DOI definition
997  * @rngcat: category list
998  * @rngcat_len: length of the category list in bytes
999  *
1000  * Description:
1001  * Checks the given categories against the given DOI definition and returns a
1002  * negative value if any of the categories do not have a valid mapping and a
1003  * zero value if all of the categories are valid.
1004  *
1005  */
1006 static int cipso_v4_map_cat_rng_valid(const struct cipso_v4_doi *doi_def,
1007 				      const unsigned char *rngcat,
1008 				      u32 rngcat_len)
1009 {
1010 	u16 cat_high;
1011 	u16 cat_low;
1012 	u32 cat_prev = CIPSO_V4_MAX_REM_CATS + 1;
1013 	u32 iter;
1014 
1015 	if (doi_def->type != CIPSO_V4_MAP_PASS || rngcat_len & 0x01)
1016 		return -EFAULT;
1017 
1018 	for (iter = 0; iter < rngcat_len; iter += 4) {
1019 		cat_high = get_unaligned_be16(&rngcat[iter]);
1020 		if ((iter + 4) <= rngcat_len)
1021 			cat_low = get_unaligned_be16(&rngcat[iter + 2]);
1022 		else
1023 			cat_low = 0;
1024 
1025 		if (cat_high > cat_prev)
1026 			return -EFAULT;
1027 
1028 		cat_prev = cat_low;
1029 	}
1030 
1031 	return 0;
1032 }
1033 
1034 /**
1035  * cipso_v4_map_cat_rng_hton - Perform a category mapping from host to network
1036  * @doi_def: the DOI definition
1037  * @secattr: the security attributes
1038  * @net_cat: the zero'd out category list in network/CIPSO format
1039  * @net_cat_len: the length of the CIPSO category list in bytes
1040  *
1041  * Description:
1042  * Perform a label mapping to translate a local MLS category bitmap to the
1043  * correct CIPSO category list using the given DOI definition.   Returns the
1044  * size in bytes of the network category bitmap on success, negative values
1045  * otherwise.
1046  *
1047  */
1048 static int cipso_v4_map_cat_rng_hton(const struct cipso_v4_doi *doi_def,
1049 				     const struct netlbl_lsm_secattr *secattr,
1050 				     unsigned char *net_cat,
1051 				     u32 net_cat_len)
1052 {
1053 	int iter = -1;
1054 	u16 array[CIPSO_V4_TAG_RNG_CAT_MAX * 2];
1055 	u32 array_cnt = 0;
1056 	u32 cat_size = 0;
1057 
1058 	/* make sure we don't overflow the 'array[]' variable */
1059 	if (net_cat_len >
1060 	    (CIPSO_V4_OPT_LEN_MAX - CIPSO_V4_HDR_LEN - CIPSO_V4_TAG_RNG_BLEN))
1061 		return -ENOSPC;
1062 
1063 	for (;;) {
1064 		iter = netlbl_catmap_walk(secattr->attr.mls.cat, iter + 1);
1065 		if (iter < 0)
1066 			break;
1067 		cat_size += (iter == 0 ? 0 : sizeof(u16));
1068 		if (cat_size > net_cat_len)
1069 			return -ENOSPC;
1070 		array[array_cnt++] = iter;
1071 
1072 		iter = netlbl_catmap_walkrng(secattr->attr.mls.cat, iter);
1073 		if (iter < 0)
1074 			return -EFAULT;
1075 		cat_size += sizeof(u16);
1076 		if (cat_size > net_cat_len)
1077 			return -ENOSPC;
1078 		array[array_cnt++] = iter;
1079 	}
1080 
1081 	for (iter = 0; array_cnt > 0;) {
1082 		*((__be16 *)&net_cat[iter]) = htons(array[--array_cnt]);
1083 		iter += 2;
1084 		array_cnt--;
1085 		if (array[array_cnt] != 0) {
1086 			*((__be16 *)&net_cat[iter]) = htons(array[array_cnt]);
1087 			iter += 2;
1088 		}
1089 	}
1090 
1091 	return cat_size;
1092 }
1093 
1094 /**
1095  * cipso_v4_map_cat_rng_ntoh - Perform a category mapping from network to host
1096  * @doi_def: the DOI definition
1097  * @net_cat: the category list in network/CIPSO format
1098  * @net_cat_len: the length of the CIPSO bitmap in bytes
1099  * @secattr: the security attributes
1100  *
1101  * Description:
1102  * Perform a label mapping to translate a CIPSO category list to the correct
1103  * local MLS category bitmap using the given DOI definition.  Returns zero on
1104  * success, negative values on failure.
1105  *
1106  */
1107 static int cipso_v4_map_cat_rng_ntoh(const struct cipso_v4_doi *doi_def,
1108 				     const unsigned char *net_cat,
1109 				     u32 net_cat_len,
1110 				     struct netlbl_lsm_secattr *secattr)
1111 {
1112 	int ret_val;
1113 	u32 net_iter;
1114 	u16 cat_low;
1115 	u16 cat_high;
1116 
1117 	for (net_iter = 0; net_iter < net_cat_len; net_iter += 4) {
1118 		cat_high = get_unaligned_be16(&net_cat[net_iter]);
1119 		if ((net_iter + 4) <= net_cat_len)
1120 			cat_low = get_unaligned_be16(&net_cat[net_iter + 2]);
1121 		else
1122 			cat_low = 0;
1123 
1124 		ret_val = netlbl_catmap_setrng(&secattr->attr.mls.cat,
1125 					       cat_low,
1126 					       cat_high,
1127 					       GFP_ATOMIC);
1128 		if (ret_val != 0)
1129 			return ret_val;
1130 	}
1131 
1132 	return 0;
1133 }
1134 
1135 /*
1136  * Protocol Handling Functions
1137  */
1138 
1139 /**
1140  * cipso_v4_gentag_hdr - Generate a CIPSO option header
1141  * @doi_def: the DOI definition
1142  * @len: the total tag length in bytes, not including this header
1143  * @buf: the CIPSO option buffer
1144  *
1145  * Description:
1146  * Write a CIPSO header into the beginning of @buffer.
1147  *
1148  */
1149 static void cipso_v4_gentag_hdr(const struct cipso_v4_doi *doi_def,
1150 				unsigned char *buf,
1151 				u32 len)
1152 {
1153 	buf[0] = IPOPT_CIPSO;
1154 	buf[1] = CIPSO_V4_HDR_LEN + len;
1155 	put_unaligned_be32(doi_def->doi, &buf[2]);
1156 }
1157 
1158 /**
1159  * cipso_v4_gentag_rbm - Generate a CIPSO restricted bitmap tag (type #1)
1160  * @doi_def: the DOI definition
1161  * @secattr: the security attributes
1162  * @buffer: the option buffer
1163  * @buffer_len: length of buffer in bytes
1164  *
1165  * Description:
1166  * Generate a CIPSO option using the restricted bitmap tag, tag type #1.  The
1167  * actual buffer length may be larger than the indicated size due to
1168  * translation between host and network category bitmaps.  Returns the size of
1169  * the tag on success, negative values on failure.
1170  *
1171  */
1172 static int cipso_v4_gentag_rbm(const struct cipso_v4_doi *doi_def,
1173 			       const struct netlbl_lsm_secattr *secattr,
1174 			       unsigned char *buffer,
1175 			       u32 buffer_len)
1176 {
1177 	int ret_val;
1178 	u32 tag_len;
1179 	u32 level;
1180 
1181 	if ((secattr->flags & NETLBL_SECATTR_MLS_LVL) == 0)
1182 		return -EPERM;
1183 
1184 	ret_val = cipso_v4_map_lvl_hton(doi_def,
1185 					secattr->attr.mls.lvl,
1186 					&level);
1187 	if (ret_val != 0)
1188 		return ret_val;
1189 
1190 	if (secattr->flags & NETLBL_SECATTR_MLS_CAT) {
1191 		ret_val = cipso_v4_map_cat_rbm_hton(doi_def,
1192 						    secattr,
1193 						    &buffer[4],
1194 						    buffer_len - 4);
1195 		if (ret_val < 0)
1196 			return ret_val;
1197 
1198 		/* This will send packets using the "optimized" format when
1199 		 * possible as specified in  section 3.4.2.6 of the
1200 		 * CIPSO draft. */
1201 		if (cipso_v4_rbm_optfmt && ret_val > 0 && ret_val <= 10)
1202 			tag_len = 14;
1203 		else
1204 			tag_len = 4 + ret_val;
1205 	} else
1206 		tag_len = 4;
1207 
1208 	buffer[0] = CIPSO_V4_TAG_RBITMAP;
1209 	buffer[1] = tag_len;
1210 	buffer[3] = level;
1211 
1212 	return tag_len;
1213 }
1214 
1215 /**
1216  * cipso_v4_parsetag_rbm - Parse a CIPSO restricted bitmap tag
1217  * @doi_def: the DOI definition
1218  * @tag: the CIPSO tag
1219  * @secattr: the security attributes
1220  *
1221  * Description:
1222  * Parse a CIPSO restricted bitmap tag (tag type #1) and return the security
1223  * attributes in @secattr.  Return zero on success, negatives values on
1224  * failure.
1225  *
1226  */
1227 static int cipso_v4_parsetag_rbm(const struct cipso_v4_doi *doi_def,
1228 				 const unsigned char *tag,
1229 				 struct netlbl_lsm_secattr *secattr)
1230 {
1231 	int ret_val;
1232 	u8 tag_len = tag[1];
1233 	u32 level;
1234 
1235 	ret_val = cipso_v4_map_lvl_ntoh(doi_def, tag[3], &level);
1236 	if (ret_val != 0)
1237 		return ret_val;
1238 	secattr->attr.mls.lvl = level;
1239 	secattr->flags |= NETLBL_SECATTR_MLS_LVL;
1240 
1241 	if (tag_len > 4) {
1242 		ret_val = cipso_v4_map_cat_rbm_ntoh(doi_def,
1243 						    &tag[4],
1244 						    tag_len - 4,
1245 						    secattr);
1246 		if (ret_val != 0) {
1247 			netlbl_catmap_free(secattr->attr.mls.cat);
1248 			return ret_val;
1249 		}
1250 
1251 		if (secattr->attr.mls.cat)
1252 			secattr->flags |= NETLBL_SECATTR_MLS_CAT;
1253 	}
1254 
1255 	return 0;
1256 }
1257 
1258 /**
1259  * cipso_v4_gentag_enum - Generate a CIPSO enumerated tag (type #2)
1260  * @doi_def: the DOI definition
1261  * @secattr: the security attributes
1262  * @buffer: the option buffer
1263  * @buffer_len: length of buffer in bytes
1264  *
1265  * Description:
1266  * Generate a CIPSO option using the enumerated tag, tag type #2.  Returns the
1267  * size of the tag on success, negative values on failure.
1268  *
1269  */
1270 static int cipso_v4_gentag_enum(const struct cipso_v4_doi *doi_def,
1271 				const struct netlbl_lsm_secattr *secattr,
1272 				unsigned char *buffer,
1273 				u32 buffer_len)
1274 {
1275 	int ret_val;
1276 	u32 tag_len;
1277 	u32 level;
1278 
1279 	if (!(secattr->flags & NETLBL_SECATTR_MLS_LVL))
1280 		return -EPERM;
1281 
1282 	ret_val = cipso_v4_map_lvl_hton(doi_def,
1283 					secattr->attr.mls.lvl,
1284 					&level);
1285 	if (ret_val != 0)
1286 		return ret_val;
1287 
1288 	if (secattr->flags & NETLBL_SECATTR_MLS_CAT) {
1289 		ret_val = cipso_v4_map_cat_enum_hton(doi_def,
1290 						     secattr,
1291 						     &buffer[4],
1292 						     buffer_len - 4);
1293 		if (ret_val < 0)
1294 			return ret_val;
1295 
1296 		tag_len = 4 + ret_val;
1297 	} else
1298 		tag_len = 4;
1299 
1300 	buffer[0] = CIPSO_V4_TAG_ENUM;
1301 	buffer[1] = tag_len;
1302 	buffer[3] = level;
1303 
1304 	return tag_len;
1305 }
1306 
1307 /**
1308  * cipso_v4_parsetag_enum - Parse a CIPSO enumerated tag
1309  * @doi_def: the DOI definition
1310  * @tag: the CIPSO tag
1311  * @secattr: the security attributes
1312  *
1313  * Description:
1314  * Parse a CIPSO enumerated tag (tag type #2) and return the security
1315  * attributes in @secattr.  Return zero on success, negatives values on
1316  * failure.
1317  *
1318  */
1319 static int cipso_v4_parsetag_enum(const struct cipso_v4_doi *doi_def,
1320 				  const unsigned char *tag,
1321 				  struct netlbl_lsm_secattr *secattr)
1322 {
1323 	int ret_val;
1324 	u8 tag_len = tag[1];
1325 	u32 level;
1326 
1327 	ret_val = cipso_v4_map_lvl_ntoh(doi_def, tag[3], &level);
1328 	if (ret_val != 0)
1329 		return ret_val;
1330 	secattr->attr.mls.lvl = level;
1331 	secattr->flags |= NETLBL_SECATTR_MLS_LVL;
1332 
1333 	if (tag_len > 4) {
1334 		ret_val = cipso_v4_map_cat_enum_ntoh(doi_def,
1335 						     &tag[4],
1336 						     tag_len - 4,
1337 						     secattr);
1338 		if (ret_val != 0) {
1339 			netlbl_catmap_free(secattr->attr.mls.cat);
1340 			return ret_val;
1341 		}
1342 
1343 		secattr->flags |= NETLBL_SECATTR_MLS_CAT;
1344 	}
1345 
1346 	return 0;
1347 }
1348 
1349 /**
1350  * cipso_v4_gentag_rng - Generate a CIPSO ranged tag (type #5)
1351  * @doi_def: the DOI definition
1352  * @secattr: the security attributes
1353  * @buffer: the option buffer
1354  * @buffer_len: length of buffer in bytes
1355  *
1356  * Description:
1357  * Generate a CIPSO option using the ranged tag, tag type #5.  Returns the
1358  * size of the tag on success, negative values on failure.
1359  *
1360  */
1361 static int cipso_v4_gentag_rng(const struct cipso_v4_doi *doi_def,
1362 			       const struct netlbl_lsm_secattr *secattr,
1363 			       unsigned char *buffer,
1364 			       u32 buffer_len)
1365 {
1366 	int ret_val;
1367 	u32 tag_len;
1368 	u32 level;
1369 
1370 	if (!(secattr->flags & NETLBL_SECATTR_MLS_LVL))
1371 		return -EPERM;
1372 
1373 	ret_val = cipso_v4_map_lvl_hton(doi_def,
1374 					secattr->attr.mls.lvl,
1375 					&level);
1376 	if (ret_val != 0)
1377 		return ret_val;
1378 
1379 	if (secattr->flags & NETLBL_SECATTR_MLS_CAT) {
1380 		ret_val = cipso_v4_map_cat_rng_hton(doi_def,
1381 						    secattr,
1382 						    &buffer[4],
1383 						    buffer_len - 4);
1384 		if (ret_val < 0)
1385 			return ret_val;
1386 
1387 		tag_len = 4 + ret_val;
1388 	} else
1389 		tag_len = 4;
1390 
1391 	buffer[0] = CIPSO_V4_TAG_RANGE;
1392 	buffer[1] = tag_len;
1393 	buffer[3] = level;
1394 
1395 	return tag_len;
1396 }
1397 
1398 /**
1399  * cipso_v4_parsetag_rng - Parse a CIPSO ranged tag
1400  * @doi_def: the DOI definition
1401  * @tag: the CIPSO tag
1402  * @secattr: the security attributes
1403  *
1404  * Description:
1405  * Parse a CIPSO ranged tag (tag type #5) and return the security attributes
1406  * in @secattr.  Return zero on success, negatives values on failure.
1407  *
1408  */
1409 static int cipso_v4_parsetag_rng(const struct cipso_v4_doi *doi_def,
1410 				 const unsigned char *tag,
1411 				 struct netlbl_lsm_secattr *secattr)
1412 {
1413 	int ret_val;
1414 	u8 tag_len = tag[1];
1415 	u32 level;
1416 
1417 	ret_val = cipso_v4_map_lvl_ntoh(doi_def, tag[3], &level);
1418 	if (ret_val != 0)
1419 		return ret_val;
1420 	secattr->attr.mls.lvl = level;
1421 	secattr->flags |= NETLBL_SECATTR_MLS_LVL;
1422 
1423 	if (tag_len > 4) {
1424 		ret_val = cipso_v4_map_cat_rng_ntoh(doi_def,
1425 						    &tag[4],
1426 						    tag_len - 4,
1427 						    secattr);
1428 		if (ret_val != 0) {
1429 			netlbl_catmap_free(secattr->attr.mls.cat);
1430 			return ret_val;
1431 		}
1432 
1433 		if (secattr->attr.mls.cat)
1434 			secattr->flags |= NETLBL_SECATTR_MLS_CAT;
1435 	}
1436 
1437 	return 0;
1438 }
1439 
1440 /**
1441  * cipso_v4_gentag_loc - Generate a CIPSO local tag (non-standard)
1442  * @doi_def: the DOI definition
1443  * @secattr: the security attributes
1444  * @buffer: the option buffer
1445  * @buffer_len: length of buffer in bytes
1446  *
1447  * Description:
1448  * Generate a CIPSO option using the local tag.  Returns the size of the tag
1449  * on success, negative values on failure.
1450  *
1451  */
1452 static int cipso_v4_gentag_loc(const struct cipso_v4_doi *doi_def,
1453 			       const struct netlbl_lsm_secattr *secattr,
1454 			       unsigned char *buffer,
1455 			       u32 buffer_len)
1456 {
1457 	if (!(secattr->flags & NETLBL_SECATTR_SECID))
1458 		return -EPERM;
1459 
1460 	buffer[0] = CIPSO_V4_TAG_LOCAL;
1461 	buffer[1] = CIPSO_V4_TAG_LOC_BLEN;
1462 	*(u32 *)&buffer[2] = secattr->attr.secid;
1463 
1464 	return CIPSO_V4_TAG_LOC_BLEN;
1465 }
1466 
1467 /**
1468  * cipso_v4_parsetag_loc - Parse a CIPSO local tag
1469  * @doi_def: the DOI definition
1470  * @tag: the CIPSO tag
1471  * @secattr: the security attributes
1472  *
1473  * Description:
1474  * Parse a CIPSO local tag and return the security attributes in @secattr.
1475  * Return zero on success, negatives values on failure.
1476  *
1477  */
1478 static int cipso_v4_parsetag_loc(const struct cipso_v4_doi *doi_def,
1479 				 const unsigned char *tag,
1480 				 struct netlbl_lsm_secattr *secattr)
1481 {
1482 	secattr->attr.secid = *(u32 *)&tag[2];
1483 	secattr->flags |= NETLBL_SECATTR_SECID;
1484 
1485 	return 0;
1486 }
1487 
1488 /**
1489  * cipso_v4_optptr - Find the CIPSO option in the packet
1490  * @skb: the packet
1491  *
1492  * Description:
1493  * Parse the packet's IP header looking for a CIPSO option.  Returns a pointer
1494  * to the start of the CIPSO option on success, NULL if one is not found.
1495  *
1496  */
1497 unsigned char *cipso_v4_optptr(const struct sk_buff *skb)
1498 {
1499 	const struct iphdr *iph = ip_hdr(skb);
1500 	unsigned char *optptr = (unsigned char *)&(ip_hdr(skb)[1]);
1501 	int optlen;
1502 	int taglen;
1503 
1504 	for (optlen = iph->ihl*4 - sizeof(struct iphdr); optlen > 1; ) {
1505 		switch (optptr[0]) {
1506 		case IPOPT_END:
1507 			return NULL;
1508 		case IPOPT_NOOP:
1509 			taglen = 1;
1510 			break;
1511 		default:
1512 			taglen = optptr[1];
1513 		}
1514 		if (!taglen || taglen > optlen)
1515 			return NULL;
1516 		if (optptr[0] == IPOPT_CIPSO)
1517 			return optptr;
1518 
1519 		optlen -= taglen;
1520 		optptr += taglen;
1521 	}
1522 
1523 	return NULL;
1524 }
1525 
1526 /**
1527  * cipso_v4_validate - Validate a CIPSO option
1528  * @skb: the packet
1529  * @option: the start of the option, on error it is set to point to the error
1530  *
1531  * Description:
1532  * This routine is called to validate a CIPSO option, it checks all of the
1533  * fields to ensure that they are at least valid, see the draft snippet below
1534  * for details.  If the option is valid then a zero value is returned and
1535  * the value of @option is unchanged.  If the option is invalid then a
1536  * non-zero value is returned and @option is adjusted to point to the
1537  * offending portion of the option.  From the IETF draft ...
1538  *
1539  *  "If any field within the CIPSO options, such as the DOI identifier, is not
1540  *   recognized the IP datagram is discarded and an ICMP 'parameter problem'
1541  *   (type 12) is generated and returned.  The ICMP code field is set to 'bad
1542  *   parameter' (code 0) and the pointer is set to the start of the CIPSO field
1543  *   that is unrecognized."
1544  *
1545  */
1546 int cipso_v4_validate(const struct sk_buff *skb, unsigned char **option)
1547 {
1548 	unsigned char *opt = *option;
1549 	unsigned char *tag;
1550 	unsigned char opt_iter;
1551 	unsigned char err_offset = 0;
1552 	u8 opt_len;
1553 	u8 tag_len;
1554 	struct cipso_v4_doi *doi_def = NULL;
1555 	u32 tag_iter;
1556 
1557 	/* caller already checks for length values that are too large */
1558 	opt_len = opt[1];
1559 	if (opt_len < 8) {
1560 		err_offset = 1;
1561 		goto validate_return;
1562 	}
1563 
1564 	rcu_read_lock();
1565 	doi_def = cipso_v4_doi_search(get_unaligned_be32(&opt[2]));
1566 	if (!doi_def) {
1567 		err_offset = 2;
1568 		goto validate_return_locked;
1569 	}
1570 
1571 	opt_iter = CIPSO_V4_HDR_LEN;
1572 	tag = opt + opt_iter;
1573 	while (opt_iter < opt_len) {
1574 		for (tag_iter = 0; doi_def->tags[tag_iter] != tag[0];)
1575 			if (doi_def->tags[tag_iter] == CIPSO_V4_TAG_INVALID ||
1576 			    ++tag_iter == CIPSO_V4_TAG_MAXCNT) {
1577 				err_offset = opt_iter;
1578 				goto validate_return_locked;
1579 			}
1580 
1581 		if (opt_iter + 1 == opt_len) {
1582 			err_offset = opt_iter;
1583 			goto validate_return_locked;
1584 		}
1585 		tag_len = tag[1];
1586 		if (tag_len > (opt_len - opt_iter)) {
1587 			err_offset = opt_iter + 1;
1588 			goto validate_return_locked;
1589 		}
1590 
1591 		switch (tag[0]) {
1592 		case CIPSO_V4_TAG_RBITMAP:
1593 			if (tag_len < CIPSO_V4_TAG_RBM_BLEN) {
1594 				err_offset = opt_iter + 1;
1595 				goto validate_return_locked;
1596 			}
1597 
1598 			/* We are already going to do all the verification
1599 			 * necessary at the socket layer so from our point of
1600 			 * view it is safe to turn these checks off (and less
1601 			 * work), however, the CIPSO draft says we should do
1602 			 * all the CIPSO validations here but it doesn't
1603 			 * really specify _exactly_ what we need to validate
1604 			 * ... so, just make it a sysctl tunable. */
1605 			if (cipso_v4_rbm_strictvalid) {
1606 				if (cipso_v4_map_lvl_valid(doi_def,
1607 							   tag[3]) < 0) {
1608 					err_offset = opt_iter + 3;
1609 					goto validate_return_locked;
1610 				}
1611 				if (tag_len > CIPSO_V4_TAG_RBM_BLEN &&
1612 				    cipso_v4_map_cat_rbm_valid(doi_def,
1613 							    &tag[4],
1614 							    tag_len - 4) < 0) {
1615 					err_offset = opt_iter + 4;
1616 					goto validate_return_locked;
1617 				}
1618 			}
1619 			break;
1620 		case CIPSO_V4_TAG_ENUM:
1621 			if (tag_len < CIPSO_V4_TAG_ENUM_BLEN) {
1622 				err_offset = opt_iter + 1;
1623 				goto validate_return_locked;
1624 			}
1625 
1626 			if (cipso_v4_map_lvl_valid(doi_def,
1627 						   tag[3]) < 0) {
1628 				err_offset = opt_iter + 3;
1629 				goto validate_return_locked;
1630 			}
1631 			if (tag_len > CIPSO_V4_TAG_ENUM_BLEN &&
1632 			    cipso_v4_map_cat_enum_valid(doi_def,
1633 							&tag[4],
1634 							tag_len - 4) < 0) {
1635 				err_offset = opt_iter + 4;
1636 				goto validate_return_locked;
1637 			}
1638 			break;
1639 		case CIPSO_V4_TAG_RANGE:
1640 			if (tag_len < CIPSO_V4_TAG_RNG_BLEN) {
1641 				err_offset = opt_iter + 1;
1642 				goto validate_return_locked;
1643 			}
1644 
1645 			if (cipso_v4_map_lvl_valid(doi_def,
1646 						   tag[3]) < 0) {
1647 				err_offset = opt_iter + 3;
1648 				goto validate_return_locked;
1649 			}
1650 			if (tag_len > CIPSO_V4_TAG_RNG_BLEN &&
1651 			    cipso_v4_map_cat_rng_valid(doi_def,
1652 						       &tag[4],
1653 						       tag_len - 4) < 0) {
1654 				err_offset = opt_iter + 4;
1655 				goto validate_return_locked;
1656 			}
1657 			break;
1658 		case CIPSO_V4_TAG_LOCAL:
1659 			/* This is a non-standard tag that we only allow for
1660 			 * local connections, so if the incoming interface is
1661 			 * not the loopback device drop the packet. Further,
1662 			 * there is no legitimate reason for setting this from
1663 			 * userspace so reject it if skb is NULL. */
1664 			if (!skb || !(skb->dev->flags & IFF_LOOPBACK)) {
1665 				err_offset = opt_iter;
1666 				goto validate_return_locked;
1667 			}
1668 			if (tag_len != CIPSO_V4_TAG_LOC_BLEN) {
1669 				err_offset = opt_iter + 1;
1670 				goto validate_return_locked;
1671 			}
1672 			break;
1673 		default:
1674 			err_offset = opt_iter;
1675 			goto validate_return_locked;
1676 		}
1677 
1678 		tag += tag_len;
1679 		opt_iter += tag_len;
1680 	}
1681 
1682 validate_return_locked:
1683 	rcu_read_unlock();
1684 validate_return:
1685 	*option = opt + err_offset;
1686 	return err_offset;
1687 }
1688 
1689 /**
1690  * cipso_v4_error - Send the correct response for a bad packet
1691  * @skb: the packet
1692  * @error: the error code
1693  * @gateway: CIPSO gateway flag
1694  *
1695  * Description:
1696  * Based on the error code given in @error, send an ICMP error message back to
1697  * the originating host.  From the IETF draft ...
1698  *
1699  *  "If the contents of the CIPSO [option] are valid but the security label is
1700  *   outside of the configured host or port label range, the datagram is
1701  *   discarded and an ICMP 'destination unreachable' (type 3) is generated and
1702  *   returned.  The code field of the ICMP is set to 'communication with
1703  *   destination network administratively prohibited' (code 9) or to
1704  *   'communication with destination host administratively prohibited'
1705  *   (code 10).  The value of the code is dependent on whether the originator
1706  *   of the ICMP message is acting as a CIPSO host or a CIPSO gateway.  The
1707  *   recipient of the ICMP message MUST be able to handle either value.  The
1708  *   same procedure is performed if a CIPSO [option] can not be added to an
1709  *   IP packet because it is too large to fit in the IP options area."
1710  *
1711  *  "If the error is triggered by receipt of an ICMP message, the message is
1712  *   discarded and no response is permitted (consistent with general ICMP
1713  *   processing rules)."
1714  *
1715  */
1716 void cipso_v4_error(struct sk_buff *skb, int error, u32 gateway)
1717 {
1718 	unsigned char optbuf[sizeof(struct ip_options) + 40];
1719 	struct ip_options *opt = (struct ip_options *)optbuf;
1720 	int res;
1721 
1722 	if (ip_hdr(skb)->protocol == IPPROTO_ICMP || error != -EACCES)
1723 		return;
1724 
1725 	/*
1726 	 * We might be called above the IP layer,
1727 	 * so we can not use icmp_send and IPCB here.
1728 	 */
1729 
1730 	memset(opt, 0, sizeof(struct ip_options));
1731 	opt->optlen = ip_hdr(skb)->ihl*4 - sizeof(struct iphdr);
1732 	rcu_read_lock();
1733 	res = __ip_options_compile(dev_net(skb->dev), opt, skb, NULL);
1734 	rcu_read_unlock();
1735 
1736 	if (res)
1737 		return;
1738 
1739 	if (gateway)
1740 		__icmp_send(skb, ICMP_DEST_UNREACH, ICMP_NET_ANO, 0, opt);
1741 	else
1742 		__icmp_send(skb, ICMP_DEST_UNREACH, ICMP_HOST_ANO, 0, opt);
1743 }
1744 
1745 /**
1746  * cipso_v4_genopt - Generate a CIPSO option
1747  * @buf: the option buffer
1748  * @buf_len: the size of opt_buf
1749  * @doi_def: the CIPSO DOI to use
1750  * @secattr: the security attributes
1751  *
1752  * Description:
1753  * Generate a CIPSO option using the DOI definition and security attributes
1754  * passed to the function.  Returns the length of the option on success and
1755  * negative values on failure.
1756  *
1757  */
1758 static int cipso_v4_genopt(unsigned char *buf, u32 buf_len,
1759 			   const struct cipso_v4_doi *doi_def,
1760 			   const struct netlbl_lsm_secattr *secattr)
1761 {
1762 	int ret_val;
1763 	u32 iter;
1764 
1765 	if (buf_len <= CIPSO_V4_HDR_LEN)
1766 		return -ENOSPC;
1767 
1768 	/* XXX - This code assumes only one tag per CIPSO option which isn't
1769 	 * really a good assumption to make but since we only support the MAC
1770 	 * tags right now it is a safe assumption. */
1771 	iter = 0;
1772 	do {
1773 		memset(buf, 0, buf_len);
1774 		switch (doi_def->tags[iter]) {
1775 		case CIPSO_V4_TAG_RBITMAP:
1776 			ret_val = cipso_v4_gentag_rbm(doi_def,
1777 						   secattr,
1778 						   &buf[CIPSO_V4_HDR_LEN],
1779 						   buf_len - CIPSO_V4_HDR_LEN);
1780 			break;
1781 		case CIPSO_V4_TAG_ENUM:
1782 			ret_val = cipso_v4_gentag_enum(doi_def,
1783 						   secattr,
1784 						   &buf[CIPSO_V4_HDR_LEN],
1785 						   buf_len - CIPSO_V4_HDR_LEN);
1786 			break;
1787 		case CIPSO_V4_TAG_RANGE:
1788 			ret_val = cipso_v4_gentag_rng(doi_def,
1789 						   secattr,
1790 						   &buf[CIPSO_V4_HDR_LEN],
1791 						   buf_len - CIPSO_V4_HDR_LEN);
1792 			break;
1793 		case CIPSO_V4_TAG_LOCAL:
1794 			ret_val = cipso_v4_gentag_loc(doi_def,
1795 						   secattr,
1796 						   &buf[CIPSO_V4_HDR_LEN],
1797 						   buf_len - CIPSO_V4_HDR_LEN);
1798 			break;
1799 		default:
1800 			return -EPERM;
1801 		}
1802 
1803 		iter++;
1804 	} while (ret_val < 0 &&
1805 		 iter < CIPSO_V4_TAG_MAXCNT &&
1806 		 doi_def->tags[iter] != CIPSO_V4_TAG_INVALID);
1807 	if (ret_val < 0)
1808 		return ret_val;
1809 	cipso_v4_gentag_hdr(doi_def, buf, ret_val);
1810 	return CIPSO_V4_HDR_LEN + ret_val;
1811 }
1812 
1813 /**
1814  * cipso_v4_sock_setattr - Add a CIPSO option to a socket
1815  * @sk: the socket
1816  * @doi_def: the CIPSO DOI to use
1817  * @secattr: the specific security attributes of the socket
1818  *
1819  * Description:
1820  * Set the CIPSO option on the given socket using the DOI definition and
1821  * security attributes passed to the function.  This function requires
1822  * exclusive access to @sk, which means it either needs to be in the
1823  * process of being created or locked.  Returns zero on success and negative
1824  * values on failure.
1825  *
1826  */
1827 int cipso_v4_sock_setattr(struct sock *sk,
1828 			  const struct cipso_v4_doi *doi_def,
1829 			  const struct netlbl_lsm_secattr *secattr)
1830 {
1831 	int ret_val = -EPERM;
1832 	unsigned char *buf = NULL;
1833 	u32 buf_len;
1834 	u32 opt_len;
1835 	struct ip_options_rcu *old, *opt = NULL;
1836 	struct inet_sock *sk_inet;
1837 	struct inet_connection_sock *sk_conn;
1838 
1839 	/* In the case of sock_create_lite(), the sock->sk field is not
1840 	 * defined yet but it is not a problem as the only users of these
1841 	 * "lite" PF_INET sockets are functions which do an accept() call
1842 	 * afterwards so we will label the socket as part of the accept(). */
1843 	if (!sk)
1844 		return 0;
1845 
1846 	/* We allocate the maximum CIPSO option size here so we are probably
1847 	 * being a little wasteful, but it makes our life _much_ easier later
1848 	 * on and after all we are only talking about 40 bytes. */
1849 	buf_len = CIPSO_V4_OPT_LEN_MAX;
1850 	buf = kmalloc(buf_len, GFP_ATOMIC);
1851 	if (!buf) {
1852 		ret_val = -ENOMEM;
1853 		goto socket_setattr_failure;
1854 	}
1855 
1856 	ret_val = cipso_v4_genopt(buf, buf_len, doi_def, secattr);
1857 	if (ret_val < 0)
1858 		goto socket_setattr_failure;
1859 	buf_len = ret_val;
1860 
1861 	/* We can't use ip_options_get() directly because it makes a call to
1862 	 * ip_options_get_alloc() which allocates memory with GFP_KERNEL and
1863 	 * we won't always have CAP_NET_RAW even though we _always_ want to
1864 	 * set the IPOPT_CIPSO option. */
1865 	opt_len = (buf_len + 3) & ~3;
1866 	opt = kzalloc(sizeof(*opt) + opt_len, GFP_ATOMIC);
1867 	if (!opt) {
1868 		ret_val = -ENOMEM;
1869 		goto socket_setattr_failure;
1870 	}
1871 	memcpy(opt->opt.__data, buf, buf_len);
1872 	opt->opt.optlen = opt_len;
1873 	opt->opt.cipso = sizeof(struct iphdr);
1874 	kfree(buf);
1875 	buf = NULL;
1876 
1877 	sk_inet = inet_sk(sk);
1878 
1879 	old = rcu_dereference_protected(sk_inet->inet_opt,
1880 					lockdep_sock_is_held(sk));
1881 	if (sk_inet->is_icsk) {
1882 		sk_conn = inet_csk(sk);
1883 		if (old)
1884 			sk_conn->icsk_ext_hdr_len -= old->opt.optlen;
1885 		sk_conn->icsk_ext_hdr_len += opt->opt.optlen;
1886 		sk_conn->icsk_sync_mss(sk, sk_conn->icsk_pmtu_cookie);
1887 	}
1888 	rcu_assign_pointer(sk_inet->inet_opt, opt);
1889 	if (old)
1890 		kfree_rcu(old, rcu);
1891 
1892 	return 0;
1893 
1894 socket_setattr_failure:
1895 	kfree(buf);
1896 	kfree(opt);
1897 	return ret_val;
1898 }
1899 
1900 /**
1901  * cipso_v4_req_setattr - Add a CIPSO option to a connection request socket
1902  * @req: the connection request socket
1903  * @doi_def: the CIPSO DOI to use
1904  * @secattr: the specific security attributes of the socket
1905  *
1906  * Description:
1907  * Set the CIPSO option on the given socket using the DOI definition and
1908  * security attributes passed to the function.  Returns zero on success and
1909  * negative values on failure.
1910  *
1911  */
1912 int cipso_v4_req_setattr(struct request_sock *req,
1913 			 const struct cipso_v4_doi *doi_def,
1914 			 const struct netlbl_lsm_secattr *secattr)
1915 {
1916 	int ret_val = -EPERM;
1917 	unsigned char *buf = NULL;
1918 	u32 buf_len;
1919 	u32 opt_len;
1920 	struct ip_options_rcu *opt = NULL;
1921 	struct inet_request_sock *req_inet;
1922 
1923 	/* We allocate the maximum CIPSO option size here so we are probably
1924 	 * being a little wasteful, but it makes our life _much_ easier later
1925 	 * on and after all we are only talking about 40 bytes. */
1926 	buf_len = CIPSO_V4_OPT_LEN_MAX;
1927 	buf = kmalloc(buf_len, GFP_ATOMIC);
1928 	if (!buf) {
1929 		ret_val = -ENOMEM;
1930 		goto req_setattr_failure;
1931 	}
1932 
1933 	ret_val = cipso_v4_genopt(buf, buf_len, doi_def, secattr);
1934 	if (ret_val < 0)
1935 		goto req_setattr_failure;
1936 	buf_len = ret_val;
1937 
1938 	/* We can't use ip_options_get() directly because it makes a call to
1939 	 * ip_options_get_alloc() which allocates memory with GFP_KERNEL and
1940 	 * we won't always have CAP_NET_RAW even though we _always_ want to
1941 	 * set the IPOPT_CIPSO option. */
1942 	opt_len = (buf_len + 3) & ~3;
1943 	opt = kzalloc(sizeof(*opt) + opt_len, GFP_ATOMIC);
1944 	if (!opt) {
1945 		ret_val = -ENOMEM;
1946 		goto req_setattr_failure;
1947 	}
1948 	memcpy(opt->opt.__data, buf, buf_len);
1949 	opt->opt.optlen = opt_len;
1950 	opt->opt.cipso = sizeof(struct iphdr);
1951 	kfree(buf);
1952 	buf = NULL;
1953 
1954 	req_inet = inet_rsk(req);
1955 	opt = xchg((__force struct ip_options_rcu **)&req_inet->ireq_opt, opt);
1956 	if (opt)
1957 		kfree_rcu(opt, rcu);
1958 
1959 	return 0;
1960 
1961 req_setattr_failure:
1962 	kfree(buf);
1963 	kfree(opt);
1964 	return ret_val;
1965 }
1966 
1967 /**
1968  * cipso_v4_delopt - Delete the CIPSO option from a set of IP options
1969  * @opt_ptr: IP option pointer
1970  *
1971  * Description:
1972  * Deletes the CIPSO IP option from a set of IP options and makes the necessary
1973  * adjustments to the IP option structure.  Returns zero on success, negative
1974  * values on failure.
1975  *
1976  */
1977 static int cipso_v4_delopt(struct ip_options_rcu __rcu **opt_ptr)
1978 {
1979 	struct ip_options_rcu *opt = rcu_dereference_protected(*opt_ptr, 1);
1980 	int hdr_delta = 0;
1981 
1982 	if (!opt || opt->opt.cipso == 0)
1983 		return 0;
1984 	if (opt->opt.srr || opt->opt.rr || opt->opt.ts || opt->opt.router_alert) {
1985 		u8 cipso_len;
1986 		u8 cipso_off;
1987 		unsigned char *cipso_ptr;
1988 		int iter;
1989 		int optlen_new;
1990 
1991 		cipso_off = opt->opt.cipso - sizeof(struct iphdr);
1992 		cipso_ptr = &opt->opt.__data[cipso_off];
1993 		cipso_len = cipso_ptr[1];
1994 
1995 		if (opt->opt.srr > opt->opt.cipso)
1996 			opt->opt.srr -= cipso_len;
1997 		if (opt->opt.rr > opt->opt.cipso)
1998 			opt->opt.rr -= cipso_len;
1999 		if (opt->opt.ts > opt->opt.cipso)
2000 			opt->opt.ts -= cipso_len;
2001 		if (opt->opt.router_alert > opt->opt.cipso)
2002 			opt->opt.router_alert -= cipso_len;
2003 		opt->opt.cipso = 0;
2004 
2005 		memmove(cipso_ptr, cipso_ptr + cipso_len,
2006 			opt->opt.optlen - cipso_off - cipso_len);
2007 
2008 		/* determining the new total option length is tricky because of
2009 		 * the padding necessary, the only thing i can think to do at
2010 		 * this point is walk the options one-by-one, skipping the
2011 		 * padding at the end to determine the actual option size and
2012 		 * from there we can determine the new total option length */
2013 		iter = 0;
2014 		optlen_new = 0;
2015 		while (iter < opt->opt.optlen)
2016 			if (opt->opt.__data[iter] != IPOPT_NOP) {
2017 				iter += opt->opt.__data[iter + 1];
2018 				optlen_new = iter;
2019 			} else
2020 				iter++;
2021 		hdr_delta = opt->opt.optlen;
2022 		opt->opt.optlen = (optlen_new + 3) & ~3;
2023 		hdr_delta -= opt->opt.optlen;
2024 	} else {
2025 		/* only the cipso option was present on the socket so we can
2026 		 * remove the entire option struct */
2027 		*opt_ptr = NULL;
2028 		hdr_delta = opt->opt.optlen;
2029 		kfree_rcu(opt, rcu);
2030 	}
2031 
2032 	return hdr_delta;
2033 }
2034 
2035 /**
2036  * cipso_v4_sock_delattr - Delete the CIPSO option from a socket
2037  * @sk: the socket
2038  *
2039  * Description:
2040  * Removes the CIPSO option from a socket, if present.
2041  *
2042  */
2043 void cipso_v4_sock_delattr(struct sock *sk)
2044 {
2045 	struct inet_sock *sk_inet;
2046 	int hdr_delta;
2047 
2048 	sk_inet = inet_sk(sk);
2049 
2050 	hdr_delta = cipso_v4_delopt(&sk_inet->inet_opt);
2051 	if (sk_inet->is_icsk && hdr_delta > 0) {
2052 		struct inet_connection_sock *sk_conn = inet_csk(sk);
2053 		sk_conn->icsk_ext_hdr_len -= hdr_delta;
2054 		sk_conn->icsk_sync_mss(sk, sk_conn->icsk_pmtu_cookie);
2055 	}
2056 }
2057 
2058 /**
2059  * cipso_v4_req_delattr - Delete the CIPSO option from a request socket
2060  * @req: the request socket
2061  *
2062  * Description:
2063  * Removes the CIPSO option from a request socket, if present.
2064  *
2065  */
2066 void cipso_v4_req_delattr(struct request_sock *req)
2067 {
2068 	cipso_v4_delopt(&inet_rsk(req)->ireq_opt);
2069 }
2070 
2071 /**
2072  * cipso_v4_getattr - Helper function for the cipso_v4_*_getattr functions
2073  * @cipso: the CIPSO v4 option
2074  * @secattr: the security attributes
2075  *
2076  * Description:
2077  * Inspect @cipso and return the security attributes in @secattr.  Returns zero
2078  * on success and negative values on failure.
2079  *
2080  */
2081 int cipso_v4_getattr(const unsigned char *cipso,
2082 		     struct netlbl_lsm_secattr *secattr)
2083 {
2084 	int ret_val = -ENOMSG;
2085 	u32 doi;
2086 	struct cipso_v4_doi *doi_def;
2087 
2088 	if (cipso_v4_cache_check(cipso, cipso[1], secattr) == 0)
2089 		return 0;
2090 
2091 	doi = get_unaligned_be32(&cipso[2]);
2092 	rcu_read_lock();
2093 	doi_def = cipso_v4_doi_search(doi);
2094 	if (!doi_def)
2095 		goto getattr_return;
2096 	/* XXX - This code assumes only one tag per CIPSO option which isn't
2097 	 * really a good assumption to make but since we only support the MAC
2098 	 * tags right now it is a safe assumption. */
2099 	switch (cipso[6]) {
2100 	case CIPSO_V4_TAG_RBITMAP:
2101 		ret_val = cipso_v4_parsetag_rbm(doi_def, &cipso[6], secattr);
2102 		break;
2103 	case CIPSO_V4_TAG_ENUM:
2104 		ret_val = cipso_v4_parsetag_enum(doi_def, &cipso[6], secattr);
2105 		break;
2106 	case CIPSO_V4_TAG_RANGE:
2107 		ret_val = cipso_v4_parsetag_rng(doi_def, &cipso[6], secattr);
2108 		break;
2109 	case CIPSO_V4_TAG_LOCAL:
2110 		ret_val = cipso_v4_parsetag_loc(doi_def, &cipso[6], secattr);
2111 		break;
2112 	}
2113 	if (ret_val == 0)
2114 		secattr->type = NETLBL_NLTYPE_CIPSOV4;
2115 
2116 getattr_return:
2117 	rcu_read_unlock();
2118 	return ret_val;
2119 }
2120 
2121 /**
2122  * cipso_v4_sock_getattr - Get the security attributes from a sock
2123  * @sk: the sock
2124  * @secattr: the security attributes
2125  *
2126  * Description:
2127  * Query @sk to see if there is a CIPSO option attached to the sock and if
2128  * there is return the CIPSO security attributes in @secattr.  This function
2129  * requires that @sk be locked, or privately held, but it does not do any
2130  * locking itself.  Returns zero on success and negative values on failure.
2131  *
2132  */
2133 int cipso_v4_sock_getattr(struct sock *sk, struct netlbl_lsm_secattr *secattr)
2134 {
2135 	struct ip_options_rcu *opt;
2136 	int res = -ENOMSG;
2137 
2138 	rcu_read_lock();
2139 	opt = rcu_dereference(inet_sk(sk)->inet_opt);
2140 	if (opt && opt->opt.cipso)
2141 		res = cipso_v4_getattr(opt->opt.__data +
2142 						opt->opt.cipso -
2143 						sizeof(struct iphdr),
2144 				       secattr);
2145 	rcu_read_unlock();
2146 	return res;
2147 }
2148 
2149 /**
2150  * cipso_v4_skbuff_setattr - Set the CIPSO option on a packet
2151  * @skb: the packet
2152  * @doi_def: the DOI structure
2153  * @secattr: the security attributes
2154  *
2155  * Description:
2156  * Set the CIPSO option on the given packet based on the security attributes.
2157  * Returns a pointer to the IP header on success and NULL on failure.
2158  *
2159  */
2160 int cipso_v4_skbuff_setattr(struct sk_buff *skb,
2161 			    const struct cipso_v4_doi *doi_def,
2162 			    const struct netlbl_lsm_secattr *secattr)
2163 {
2164 	int ret_val;
2165 	struct iphdr *iph;
2166 	struct ip_options *opt = &IPCB(skb)->opt;
2167 	unsigned char buf[CIPSO_V4_OPT_LEN_MAX];
2168 	u32 buf_len = CIPSO_V4_OPT_LEN_MAX;
2169 	u32 opt_len;
2170 	int len_delta;
2171 
2172 	ret_val = cipso_v4_genopt(buf, buf_len, doi_def, secattr);
2173 	if (ret_val < 0)
2174 		return ret_val;
2175 	buf_len = ret_val;
2176 	opt_len = (buf_len + 3) & ~3;
2177 
2178 	/* we overwrite any existing options to ensure that we have enough
2179 	 * room for the CIPSO option, the reason is that we _need_ to guarantee
2180 	 * that the security label is applied to the packet - we do the same
2181 	 * thing when using the socket options and it hasn't caused a problem,
2182 	 * if we need to we can always revisit this choice later */
2183 
2184 	len_delta = opt_len - opt->optlen;
2185 	/* if we don't ensure enough headroom we could panic on the skb_push()
2186 	 * call below so make sure we have enough, we are also "mangling" the
2187 	 * packet so we should probably do a copy-on-write call anyway */
2188 	ret_val = skb_cow(skb, skb_headroom(skb) + len_delta);
2189 	if (ret_val < 0)
2190 		return ret_val;
2191 
2192 	if (len_delta > 0) {
2193 		/* we assume that the header + opt->optlen have already been
2194 		 * "pushed" in ip_options_build() or similar */
2195 		iph = ip_hdr(skb);
2196 		skb_push(skb, len_delta);
2197 		memmove((char *)iph - len_delta, iph, iph->ihl << 2);
2198 		skb_reset_network_header(skb);
2199 		iph = ip_hdr(skb);
2200 	} else if (len_delta < 0) {
2201 		iph = ip_hdr(skb);
2202 		memset(iph + 1, IPOPT_NOP, opt->optlen);
2203 	} else
2204 		iph = ip_hdr(skb);
2205 
2206 	if (opt->optlen > 0)
2207 		memset(opt, 0, sizeof(*opt));
2208 	opt->optlen = opt_len;
2209 	opt->cipso = sizeof(struct iphdr);
2210 	opt->is_changed = 1;
2211 
2212 	/* we have to do the following because we are being called from a
2213 	 * netfilter hook which means the packet already has had the header
2214 	 * fields populated and the checksum calculated - yes this means we
2215 	 * are doing more work than needed but we do it to keep the core
2216 	 * stack clean and tidy */
2217 	memcpy(iph + 1, buf, buf_len);
2218 	if (opt_len > buf_len)
2219 		memset((char *)(iph + 1) + buf_len, 0, opt_len - buf_len);
2220 	if (len_delta != 0) {
2221 		iph->ihl = 5 + (opt_len >> 2);
2222 		iph->tot_len = htons(skb->len);
2223 	}
2224 	ip_send_check(iph);
2225 
2226 	return 0;
2227 }
2228 
2229 /**
2230  * cipso_v4_skbuff_delattr - Delete any CIPSO options from a packet
2231  * @skb: the packet
2232  *
2233  * Description:
2234  * Removes any and all CIPSO options from the given packet.  Returns zero on
2235  * success, negative values on failure.
2236  *
2237  */
2238 int cipso_v4_skbuff_delattr(struct sk_buff *skb)
2239 {
2240 	int ret_val;
2241 	struct iphdr *iph;
2242 	struct ip_options *opt = &IPCB(skb)->opt;
2243 	unsigned char *cipso_ptr;
2244 
2245 	if (opt->cipso == 0)
2246 		return 0;
2247 
2248 	/* since we are changing the packet we should make a copy */
2249 	ret_val = skb_cow(skb, skb_headroom(skb));
2250 	if (ret_val < 0)
2251 		return ret_val;
2252 
2253 	/* the easiest thing to do is just replace the cipso option with noop
2254 	 * options since we don't change the size of the packet, although we
2255 	 * still need to recalculate the checksum */
2256 
2257 	iph = ip_hdr(skb);
2258 	cipso_ptr = (unsigned char *)iph + opt->cipso;
2259 	memset(cipso_ptr, IPOPT_NOOP, cipso_ptr[1]);
2260 	opt->cipso = 0;
2261 	opt->is_changed = 1;
2262 
2263 	ip_send_check(iph);
2264 
2265 	return 0;
2266 }
2267 
2268 /*
2269  * Setup Functions
2270  */
2271 
2272 /**
2273  * cipso_v4_init - Initialize the CIPSO module
2274  *
2275  * Description:
2276  * Initialize the CIPSO module and prepare it for use.  Returns zero on success
2277  * and negative values on failure.
2278  *
2279  */
2280 static int __init cipso_v4_init(void)
2281 {
2282 	int ret_val;
2283 
2284 	ret_val = cipso_v4_cache_init();
2285 	if (ret_val != 0)
2286 		panic("Failed to initialize the CIPSO/IPv4 cache (%d)\n",
2287 		      ret_val);
2288 
2289 	return 0;
2290 }
2291 
2292 subsys_initcall(cipso_v4_init);
2293