Merge ../linus
[pandora-kernel.git] / net / ipv4 / cipso_ipv4.c
1 /*
2  * CIPSO - Commercial IP Security Option
3  *
4  * This is an implementation of the CIPSO 2.2 protocol as specified in
5  * draft-ietf-cipso-ipsecurity-01.txt with additional tag types as found in
6  * FIPS-188, copies of both documents can be found in the Documentation
7  * directory.  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  * Author: Paul Moore <paul.moore@hp.com>
12  *
13  */
14
15 /*
16  * (c) Copyright Hewlett-Packard Development Company, L.P., 2006
17  *
18  * This program is free software;  you can redistribute it and/or modify
19  * it under the terms of the GNU General Public License as published by
20  * the Free Software Foundation; either version 2 of the License, or
21  * (at your option) any later version.
22  *
23  * This program is distributed in the hope that it will be useful,
24  * but WITHOUT ANY WARRANTY;  without even the implied warranty of
25  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
26  * the GNU General Public License for more details.
27  *
28  * You should have received a copy of the GNU General Public License
29  * along with this program;  if not, write to the Free Software
30  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
31  *
32  */
33
34 #include <linux/init.h>
35 #include <linux/types.h>
36 #include <linux/rcupdate.h>
37 #include <linux/list.h>
38 #include <linux/spinlock.h>
39 #include <linux/string.h>
40 #include <linux/jhash.h>
41 #include <net/ip.h>
42 #include <net/icmp.h>
43 #include <net/tcp.h>
44 #include <net/netlabel.h>
45 #include <net/cipso_ipv4.h>
46 #include <asm/atomic.h>
47 #include <asm/bug.h>
48
49 struct cipso_v4_domhsh_entry {
50         char *domain;
51         u32 valid;
52         struct list_head list;
53         struct rcu_head rcu;
54 };
55
56 /* List of available DOI definitions */
57 /* XXX - Updates should be minimal so having a single lock for the
58  * cipso_v4_doi_list and the cipso_v4_doi_list->dom_list should be
59  * okay. */
60 /* XXX - This currently assumes a minimal number of different DOIs in use,
61  * if in practice there are a lot of different DOIs this list should
62  * probably be turned into a hash table or something similar so we
63  * can do quick lookups. */
64 static DEFINE_SPINLOCK(cipso_v4_doi_list_lock);
65 static struct list_head cipso_v4_doi_list = LIST_HEAD_INIT(cipso_v4_doi_list);
66
67 /* Label mapping cache */
68 int cipso_v4_cache_enabled = 1;
69 int cipso_v4_cache_bucketsize = 10;
70 #define CIPSO_V4_CACHE_BUCKETBITS     7
71 #define CIPSO_V4_CACHE_BUCKETS        (1 << CIPSO_V4_CACHE_BUCKETBITS)
72 #define CIPSO_V4_CACHE_REORDERLIMIT   10
73 struct cipso_v4_map_cache_bkt {
74         spinlock_t lock;
75         u32 size;
76         struct list_head list;
77 };
78 struct cipso_v4_map_cache_entry {
79         u32 hash;
80         unsigned char *key;
81         size_t key_len;
82
83         struct netlbl_lsm_cache *lsm_data;
84
85         u32 activity;
86         struct list_head list;
87 };
88 static struct cipso_v4_map_cache_bkt *cipso_v4_cache = NULL;
89
90 /* Restricted bitmap (tag #1) flags */
91 int cipso_v4_rbm_optfmt = 0;
92 int cipso_v4_rbm_strictvalid = 1;
93
94 /*
95  * Helper Functions
96  */
97
98 /**
99  * cipso_v4_bitmap_walk - Walk a bitmap looking for a bit
100  * @bitmap: the bitmap
101  * @bitmap_len: length in bits
102  * @offset: starting offset
103  * @state: if non-zero, look for a set (1) bit else look for a cleared (0) bit
104  *
105  * Description:
106  * Starting at @offset, walk the bitmap from left to right until either the
107  * desired bit is found or we reach the end.  Return the bit offset, -1 if
108  * not found, or -2 if error.
109  */
110 static int cipso_v4_bitmap_walk(const unsigned char *bitmap,
111                                 u32 bitmap_len,
112                                 u32 offset,
113                                 u8 state)
114 {
115         u32 bit_spot;
116         u32 byte_offset;
117         unsigned char bitmask;
118         unsigned char byte;
119
120         /* gcc always rounds to zero when doing integer division */
121         byte_offset = offset / 8;
122         byte = bitmap[byte_offset];
123         bit_spot = offset;
124         bitmask = 0x80 >> (offset % 8);
125
126         while (bit_spot < bitmap_len) {
127                 if ((state && (byte & bitmask) == bitmask) ||
128                     (state == 0 && (byte & bitmask) == 0))
129                         return bit_spot;
130
131                 bit_spot++;
132                 bitmask >>= 1;
133                 if (bitmask == 0) {
134                         byte = bitmap[++byte_offset];
135                         bitmask = 0x80;
136                 }
137         }
138
139         return -1;
140 }
141
142 /**
143  * cipso_v4_bitmap_setbit - Sets a single bit in a bitmap
144  * @bitmap: the bitmap
145  * @bit: the bit
146  * @state: if non-zero, set the bit (1) else clear the bit (0)
147  *
148  * Description:
149  * Set a single bit in the bitmask.  Returns zero on success, negative values
150  * on error.
151  */
152 static void cipso_v4_bitmap_setbit(unsigned char *bitmap,
153                                    u32 bit,
154                                    u8 state)
155 {
156         u32 byte_spot;
157         u8 bitmask;
158
159         /* gcc always rounds to zero when doing integer division */
160         byte_spot = bit / 8;
161         bitmask = 0x80 >> (bit % 8);
162         if (state)
163                 bitmap[byte_spot] |= bitmask;
164         else
165                 bitmap[byte_spot] &= ~bitmask;
166 }
167
168 /**
169  * cipso_v4_doi_domhsh_free - Frees a domain list entry
170  * @entry: the entry's RCU field
171  *
172  * Description:
173  * This function is designed to be used as a callback to the call_rcu()
174  * function so that the memory allocated to a domain list entry can be released
175  * safely.
176  *
177  */
178 static void cipso_v4_doi_domhsh_free(struct rcu_head *entry)
179 {
180         struct cipso_v4_domhsh_entry *ptr;
181
182         ptr = container_of(entry, struct cipso_v4_domhsh_entry, rcu);
183         kfree(ptr->domain);
184         kfree(ptr);
185 }
186
187 /**
188  * cipso_v4_cache_entry_free - Frees a cache entry
189  * @entry: the entry to free
190  *
191  * Description:
192  * This function frees the memory associated with a cache entry including the
193  * LSM cache data if there are no longer any users, i.e. reference count == 0.
194  *
195  */
196 static void cipso_v4_cache_entry_free(struct cipso_v4_map_cache_entry *entry)
197 {
198         if (entry->lsm_data)
199                 netlbl_secattr_cache_free(entry->lsm_data);
200         kfree(entry->key);
201         kfree(entry);
202 }
203
204 /**
205  * cipso_v4_map_cache_hash - Hashing function for the CIPSO cache
206  * @key: the hash key
207  * @key_len: the length of the key in bytes
208  *
209  * Description:
210  * The CIPSO tag hashing function.  Returns a 32-bit hash value.
211  *
212  */
213 static u32 cipso_v4_map_cache_hash(const unsigned char *key, u32 key_len)
214 {
215         return jhash(key, key_len, 0);
216 }
217
218 /*
219  * Label Mapping Cache Functions
220  */
221
222 /**
223  * cipso_v4_cache_init - Initialize the CIPSO cache
224  *
225  * Description:
226  * Initializes the CIPSO label mapping cache, this function should be called
227  * before any of the other functions defined in this file.  Returns zero on
228  * success, negative values on error.
229  *
230  */
231 static int cipso_v4_cache_init(void)
232 {
233         u32 iter;
234
235         cipso_v4_cache = kcalloc(CIPSO_V4_CACHE_BUCKETS,
236                                  sizeof(struct cipso_v4_map_cache_bkt),
237                                  GFP_KERNEL);
238         if (cipso_v4_cache == NULL)
239                 return -ENOMEM;
240
241         for (iter = 0; iter < CIPSO_V4_CACHE_BUCKETS; iter++) {
242                 spin_lock_init(&cipso_v4_cache[iter].lock);
243                 cipso_v4_cache[iter].size = 0;
244                 INIT_LIST_HEAD(&cipso_v4_cache[iter].list);
245         }
246
247         return 0;
248 }
249
250 /**
251  * cipso_v4_cache_invalidate - Invalidates the current CIPSO cache
252  *
253  * Description:
254  * Invalidates and frees any entries in the CIPSO cache.  Returns zero on
255  * success and negative values on failure.
256  *
257  */
258 void cipso_v4_cache_invalidate(void)
259 {
260         struct cipso_v4_map_cache_entry *entry, *tmp_entry;
261         u32 iter;
262
263         for (iter = 0; iter < CIPSO_V4_CACHE_BUCKETS; iter++) {
264                 spin_lock_bh(&cipso_v4_cache[iter].lock);
265                 list_for_each_entry_safe(entry,
266                                          tmp_entry,
267                                          &cipso_v4_cache[iter].list, list) {
268                         list_del(&entry->list);
269                         cipso_v4_cache_entry_free(entry);
270                 }
271                 cipso_v4_cache[iter].size = 0;
272                 spin_unlock_bh(&cipso_v4_cache[iter].lock);
273         }
274
275         return;
276 }
277
278 /**
279  * cipso_v4_cache_check - Check the CIPSO cache for a label mapping
280  * @key: the buffer to check
281  * @key_len: buffer length in bytes
282  * @secattr: the security attribute struct to use
283  *
284  * Description:
285  * This function checks the cache to see if a label mapping already exists for
286  * the given key.  If there is a match then the cache is adjusted and the
287  * @secattr struct is populated with the correct LSM security attributes.  The
288  * cache is adjusted in the following manner if the entry is not already the
289  * first in the cache bucket:
290  *
291  *  1. The cache entry's activity counter is incremented
292  *  2. The previous (higher ranking) entry's activity counter is decremented
293  *  3. If the difference between the two activity counters is geater than
294  *     CIPSO_V4_CACHE_REORDERLIMIT the two entries are swapped
295  *
296  * Returns zero on success, -ENOENT for a cache miss, and other negative values
297  * on error.
298  *
299  */
300 static int cipso_v4_cache_check(const unsigned char *key,
301                                 u32 key_len,
302                                 struct netlbl_lsm_secattr *secattr)
303 {
304         u32 bkt;
305         struct cipso_v4_map_cache_entry *entry;
306         struct cipso_v4_map_cache_entry *prev_entry = NULL;
307         u32 hash;
308
309         if (!cipso_v4_cache_enabled)
310                 return -ENOENT;
311
312         hash = cipso_v4_map_cache_hash(key, key_len);
313         bkt = hash & (CIPSO_V4_CACHE_BUCKETBITS - 1);
314         spin_lock_bh(&cipso_v4_cache[bkt].lock);
315         list_for_each_entry(entry, &cipso_v4_cache[bkt].list, list) {
316                 if (entry->hash == hash &&
317                     entry->key_len == key_len &&
318                     memcmp(entry->key, key, key_len) == 0) {
319                         entry->activity += 1;
320                         atomic_inc(&entry->lsm_data->refcount);
321                         secattr->cache = entry->lsm_data;
322                         secattr->flags |= NETLBL_SECATTR_CACHE;
323                         if (prev_entry == NULL) {
324                                 spin_unlock_bh(&cipso_v4_cache[bkt].lock);
325                                 return 0;
326                         }
327
328                         if (prev_entry->activity > 0)
329                                 prev_entry->activity -= 1;
330                         if (entry->activity > prev_entry->activity &&
331                             entry->activity - prev_entry->activity >
332                             CIPSO_V4_CACHE_REORDERLIMIT) {
333                                 __list_del(entry->list.prev, entry->list.next);
334                                 __list_add(&entry->list,
335                                            prev_entry->list.prev,
336                                            &prev_entry->list);
337                         }
338
339                         spin_unlock_bh(&cipso_v4_cache[bkt].lock);
340                         return 0;
341                 }
342                 prev_entry = entry;
343         }
344         spin_unlock_bh(&cipso_v4_cache[bkt].lock);
345
346         return -ENOENT;
347 }
348
349 /**
350  * cipso_v4_cache_add - Add an entry to the CIPSO cache
351  * @skb: the packet
352  * @secattr: the packet's security attributes
353  *
354  * Description:
355  * Add a new entry into the CIPSO label mapping cache.  Add the new entry to
356  * head of the cache bucket's list, if the cache bucket is out of room remove
357  * the last entry in the list first.  It is important to note that there is
358  * currently no checking for duplicate keys.  Returns zero on success,
359  * negative values on failure.
360  *
361  */
362 int cipso_v4_cache_add(const struct sk_buff *skb,
363                        const struct netlbl_lsm_secattr *secattr)
364 {
365         int ret_val = -EPERM;
366         u32 bkt;
367         struct cipso_v4_map_cache_entry *entry = NULL;
368         struct cipso_v4_map_cache_entry *old_entry = NULL;
369         unsigned char *cipso_ptr;
370         u32 cipso_ptr_len;
371
372         if (!cipso_v4_cache_enabled || cipso_v4_cache_bucketsize <= 0)
373                 return 0;
374
375         cipso_ptr = CIPSO_V4_OPTPTR(skb);
376         cipso_ptr_len = cipso_ptr[1];
377
378         entry = kzalloc(sizeof(*entry), GFP_ATOMIC);
379         if (entry == NULL)
380                 return -ENOMEM;
381         entry->key = kmemdup(cipso_ptr, cipso_ptr_len, GFP_ATOMIC);
382         if (entry->key == NULL) {
383                 ret_val = -ENOMEM;
384                 goto cache_add_failure;
385         }
386         entry->key_len = cipso_ptr_len;
387         entry->hash = cipso_v4_map_cache_hash(cipso_ptr, cipso_ptr_len);
388         atomic_inc(&secattr->cache->refcount);
389         entry->lsm_data = secattr->cache;
390
391         bkt = entry->hash & (CIPSO_V4_CACHE_BUCKETBITS - 1);
392         spin_lock_bh(&cipso_v4_cache[bkt].lock);
393         if (cipso_v4_cache[bkt].size < cipso_v4_cache_bucketsize) {
394                 list_add(&entry->list, &cipso_v4_cache[bkt].list);
395                 cipso_v4_cache[bkt].size += 1;
396         } else {
397                 old_entry = list_entry(cipso_v4_cache[bkt].list.prev,
398                                        struct cipso_v4_map_cache_entry, list);
399                 list_del(&old_entry->list);
400                 list_add(&entry->list, &cipso_v4_cache[bkt].list);
401                 cipso_v4_cache_entry_free(old_entry);
402         }
403         spin_unlock_bh(&cipso_v4_cache[bkt].lock);
404
405         return 0;
406
407 cache_add_failure:
408         if (entry)
409                 cipso_v4_cache_entry_free(entry);
410         return ret_val;
411 }
412
413 /*
414  * DOI List Functions
415  */
416
417 /**
418  * cipso_v4_doi_search - Searches for a DOI definition
419  * @doi: the DOI to search for
420  *
421  * Description:
422  * Search the DOI definition list for a DOI definition with a DOI value that
423  * matches @doi.  The caller is responsibile for calling rcu_read_[un]lock().
424  * Returns a pointer to the DOI definition on success and NULL on failure.
425  */
426 static struct cipso_v4_doi *cipso_v4_doi_search(u32 doi)
427 {
428         struct cipso_v4_doi *iter;
429
430         list_for_each_entry_rcu(iter, &cipso_v4_doi_list, list)
431                 if (iter->doi == doi && iter->valid)
432                         return iter;
433         return NULL;
434 }
435
436 /**
437  * cipso_v4_doi_add - Add a new DOI to the CIPSO protocol engine
438  * @doi_def: the DOI structure
439  *
440  * Description:
441  * The caller defines a new DOI for use by the CIPSO engine and calls this
442  * function to add it to the list of acceptable domains.  The caller must
443  * ensure that the mapping table specified in @doi_def->map meets all of the
444  * requirements of the mapping type (see cipso_ipv4.h for details).  Returns
445  * zero on success and non-zero on failure.
446  *
447  */
448 int cipso_v4_doi_add(struct cipso_v4_doi *doi_def)
449 {
450         u32 iter;
451
452         if (doi_def == NULL || doi_def->doi == CIPSO_V4_DOI_UNKNOWN)
453                 return -EINVAL;
454         for (iter = 0; iter < CIPSO_V4_TAG_MAXCNT; iter++) {
455                 switch (doi_def->tags[iter]) {
456                 case CIPSO_V4_TAG_RBITMAP:
457                         break;
458                 case CIPSO_V4_TAG_RANGE:
459                         if (doi_def->type != CIPSO_V4_MAP_PASS)
460                                 return -EINVAL;
461                         break;
462                 case CIPSO_V4_TAG_INVALID:
463                         if (iter == 0)
464                                 return -EINVAL;
465                         break;
466                 case CIPSO_V4_TAG_ENUM:
467                         if (doi_def->type != CIPSO_V4_MAP_PASS)
468                                 return -EINVAL;
469                         break;
470                 default:
471                         return -EINVAL;
472                 }
473         }
474
475         doi_def->valid = 1;
476         INIT_RCU_HEAD(&doi_def->rcu);
477         INIT_LIST_HEAD(&doi_def->dom_list);
478
479         rcu_read_lock();
480         if (cipso_v4_doi_search(doi_def->doi) != NULL)
481                 goto doi_add_failure_rlock;
482         spin_lock(&cipso_v4_doi_list_lock);
483         if (cipso_v4_doi_search(doi_def->doi) != NULL)
484                 goto doi_add_failure_slock;
485         list_add_tail_rcu(&doi_def->list, &cipso_v4_doi_list);
486         spin_unlock(&cipso_v4_doi_list_lock);
487         rcu_read_unlock();
488
489         return 0;
490
491 doi_add_failure_slock:
492         spin_unlock(&cipso_v4_doi_list_lock);
493 doi_add_failure_rlock:
494         rcu_read_unlock();
495         return -EEXIST;
496 }
497
498 /**
499  * cipso_v4_doi_remove - Remove an existing DOI from the CIPSO protocol engine
500  * @doi: the DOI value
501  * @audit_secid: the LSM secid to use in the audit message
502  * @callback: the DOI cleanup/free callback
503  *
504  * Description:
505  * Removes a DOI definition from the CIPSO engine, @callback is called to
506  * free any memory.  The NetLabel routines will be called to release their own
507  * LSM domain mappings as well as our own domain list.  Returns zero on
508  * success and negative values on failure.
509  *
510  */
511 int cipso_v4_doi_remove(u32 doi,
512                         struct netlbl_audit *audit_info,
513                         void (*callback) (struct rcu_head * head))
514 {
515         struct cipso_v4_doi *doi_def;
516         struct cipso_v4_domhsh_entry *dom_iter;
517
518         rcu_read_lock();
519         if (cipso_v4_doi_search(doi) != NULL) {
520                 spin_lock(&cipso_v4_doi_list_lock);
521                 doi_def = cipso_v4_doi_search(doi);
522                 if (doi_def == NULL) {
523                         spin_unlock(&cipso_v4_doi_list_lock);
524                         rcu_read_unlock();
525                         return -ENOENT;
526                 }
527                 doi_def->valid = 0;
528                 list_del_rcu(&doi_def->list);
529                 spin_unlock(&cipso_v4_doi_list_lock);
530                 list_for_each_entry_rcu(dom_iter, &doi_def->dom_list, list)
531                         if (dom_iter->valid)
532                                 netlbl_domhsh_remove(dom_iter->domain,
533                                                      audit_info);
534                 cipso_v4_cache_invalidate();
535                 rcu_read_unlock();
536
537                 call_rcu(&doi_def->rcu, callback);
538                 return 0;
539         }
540         rcu_read_unlock();
541
542         return -ENOENT;
543 }
544
545 /**
546  * cipso_v4_doi_getdef - Returns a pointer to a valid DOI definition
547  * @doi: the DOI value
548  *
549  * Description:
550  * Searches for a valid DOI definition and if one is found it is returned to
551  * the caller.  Otherwise NULL is returned.  The caller must ensure that
552  * rcu_read_lock() is held while accessing the returned definition.
553  *
554  */
555 struct cipso_v4_doi *cipso_v4_doi_getdef(u32 doi)
556 {
557         return cipso_v4_doi_search(doi);
558 }
559
560 /**
561  * cipso_v4_doi_walk - Iterate through the DOI definitions
562  * @skip_cnt: skip past this number of DOI definitions, updated
563  * @callback: callback for each DOI definition
564  * @cb_arg: argument for the callback function
565  *
566  * Description:
567  * Iterate over the DOI definition list, skipping the first @skip_cnt entries.
568  * For each entry call @callback, if @callback returns a negative value stop
569  * 'walking' through the list and return.  Updates the value in @skip_cnt upon
570  * return.  Returns zero on success, negative values on failure.
571  *
572  */
573 int cipso_v4_doi_walk(u32 *skip_cnt,
574                      int (*callback) (struct cipso_v4_doi *doi_def, void *arg),
575                      void *cb_arg)
576 {
577         int ret_val = -ENOENT;
578         u32 doi_cnt = 0;
579         struct cipso_v4_doi *iter_doi;
580
581         rcu_read_lock();
582         list_for_each_entry_rcu(iter_doi, &cipso_v4_doi_list, list)
583                 if (iter_doi->valid) {
584                         if (doi_cnt++ < *skip_cnt)
585                                 continue;
586                         ret_val = callback(iter_doi, cb_arg);
587                         if (ret_val < 0) {
588                                 doi_cnt--;
589                                 goto doi_walk_return;
590                         }
591                 }
592
593 doi_walk_return:
594         rcu_read_unlock();
595         *skip_cnt = doi_cnt;
596         return ret_val;
597 }
598
599 /**
600  * cipso_v4_doi_domhsh_add - Adds a domain entry to a DOI definition
601  * @doi_def: the DOI definition
602  * @domain: the domain to add
603  *
604  * Description:
605  * Adds the @domain to the the DOI specified by @doi_def, this function
606  * should only be called by external functions (i.e. NetLabel).  This function
607  * does allocate memory.  Returns zero on success, negative values on failure.
608  *
609  */
610 int cipso_v4_doi_domhsh_add(struct cipso_v4_doi *doi_def, const char *domain)
611 {
612         struct cipso_v4_domhsh_entry *iter;
613         struct cipso_v4_domhsh_entry *new_dom;
614
615         new_dom = kzalloc(sizeof(*new_dom), GFP_KERNEL);
616         if (new_dom == NULL)
617                 return -ENOMEM;
618         if (domain) {
619                 new_dom->domain = kstrdup(domain, GFP_KERNEL);
620                 if (new_dom->domain == NULL) {
621                         kfree(new_dom);
622                         return -ENOMEM;
623                 }
624         }
625         new_dom->valid = 1;
626         INIT_RCU_HEAD(&new_dom->rcu);
627
628         rcu_read_lock();
629         spin_lock(&cipso_v4_doi_list_lock);
630         list_for_each_entry_rcu(iter, &doi_def->dom_list, list)
631                 if (iter->valid &&
632                     ((domain != NULL && iter->domain != NULL &&
633                       strcmp(iter->domain, domain) == 0) ||
634                      (domain == NULL && iter->domain == NULL))) {
635                         spin_unlock(&cipso_v4_doi_list_lock);
636                         rcu_read_unlock();
637                         kfree(new_dom->domain);
638                         kfree(new_dom);
639                         return -EEXIST;
640                 }
641         list_add_tail_rcu(&new_dom->list, &doi_def->dom_list);
642         spin_unlock(&cipso_v4_doi_list_lock);
643         rcu_read_unlock();
644
645         return 0;
646 }
647
648 /**
649  * cipso_v4_doi_domhsh_remove - Removes a domain entry from a DOI definition
650  * @doi_def: the DOI definition
651  * @domain: the domain to remove
652  *
653  * Description:
654  * Removes the @domain from the DOI specified by @doi_def, this function
655  * should only be called by external functions (i.e. NetLabel).   Returns zero
656  * on success and negative values on error.
657  *
658  */
659 int cipso_v4_doi_domhsh_remove(struct cipso_v4_doi *doi_def,
660                                const char *domain)
661 {
662         struct cipso_v4_domhsh_entry *iter;
663
664         rcu_read_lock();
665         spin_lock(&cipso_v4_doi_list_lock);
666         list_for_each_entry_rcu(iter, &doi_def->dom_list, list)
667                 if (iter->valid &&
668                     ((domain != NULL && iter->domain != NULL &&
669                       strcmp(iter->domain, domain) == 0) ||
670                      (domain == NULL && iter->domain == NULL))) {
671                         iter->valid = 0;
672                         list_del_rcu(&iter->list);
673                         spin_unlock(&cipso_v4_doi_list_lock);
674                         rcu_read_unlock();
675                         call_rcu(&iter->rcu, cipso_v4_doi_domhsh_free);
676
677                         return 0;
678                 }
679         spin_unlock(&cipso_v4_doi_list_lock);
680         rcu_read_unlock();
681
682         return -ENOENT;
683 }
684
685 /*
686  * Label Mapping Functions
687  */
688
689 /**
690  * cipso_v4_map_lvl_valid - Checks to see if the given level is understood
691  * @doi_def: the DOI definition
692  * @level: the level to check
693  *
694  * Description:
695  * Checks the given level against the given DOI definition and returns a
696  * negative value if the level does not have a valid mapping and a zero value
697  * if the level is defined by the DOI.
698  *
699  */
700 static int cipso_v4_map_lvl_valid(const struct cipso_v4_doi *doi_def, u8 level)
701 {
702         switch (doi_def->type) {
703         case CIPSO_V4_MAP_PASS:
704                 return 0;
705         case CIPSO_V4_MAP_STD:
706                 if (doi_def->map.std->lvl.cipso[level] < CIPSO_V4_INV_LVL)
707                         return 0;
708                 break;
709         }
710
711         return -EFAULT;
712 }
713
714 /**
715  * cipso_v4_map_lvl_hton - Perform a level mapping from the host to the network
716  * @doi_def: the DOI definition
717  * @host_lvl: the host MLS level
718  * @net_lvl: the network/CIPSO MLS level
719  *
720  * Description:
721  * Perform a label mapping to translate a local MLS level to the correct
722  * CIPSO level using the given DOI definition.  Returns zero on success,
723  * negative values otherwise.
724  *
725  */
726 static int cipso_v4_map_lvl_hton(const struct cipso_v4_doi *doi_def,
727                                  u32 host_lvl,
728                                  u32 *net_lvl)
729 {
730         switch (doi_def->type) {
731         case CIPSO_V4_MAP_PASS:
732                 *net_lvl = host_lvl;
733                 return 0;
734         case CIPSO_V4_MAP_STD:
735                 if (host_lvl < doi_def->map.std->lvl.local_size) {
736                         *net_lvl = doi_def->map.std->lvl.local[host_lvl];
737                         return 0;
738                 }
739                 break;
740         }
741
742         return -EINVAL;
743 }
744
745 /**
746  * cipso_v4_map_lvl_ntoh - Perform a level mapping from the network to the host
747  * @doi_def: the DOI definition
748  * @net_lvl: the network/CIPSO MLS level
749  * @host_lvl: the host MLS level
750  *
751  * Description:
752  * Perform a label mapping to translate a CIPSO level to the correct local MLS
753  * level using the given DOI definition.  Returns zero on success, negative
754  * values otherwise.
755  *
756  */
757 static int cipso_v4_map_lvl_ntoh(const struct cipso_v4_doi *doi_def,
758                                  u32 net_lvl,
759                                  u32 *host_lvl)
760 {
761         struct cipso_v4_std_map_tbl *map_tbl;
762
763         switch (doi_def->type) {
764         case CIPSO_V4_MAP_PASS:
765                 *host_lvl = net_lvl;
766                 return 0;
767         case CIPSO_V4_MAP_STD:
768                 map_tbl = doi_def->map.std;
769                 if (net_lvl < map_tbl->lvl.cipso_size &&
770                     map_tbl->lvl.cipso[net_lvl] < CIPSO_V4_INV_LVL) {
771                         *host_lvl = doi_def->map.std->lvl.cipso[net_lvl];
772                         return 0;
773                 }
774                 break;
775         }
776
777         return -EINVAL;
778 }
779
780 /**
781  * cipso_v4_map_cat_rbm_valid - Checks to see if the category bitmap is valid
782  * @doi_def: the DOI definition
783  * @bitmap: category bitmap
784  * @bitmap_len: bitmap length in bytes
785  *
786  * Description:
787  * Checks the given category bitmap against the given DOI definition and
788  * returns a negative value if any of the categories in the bitmap do not have
789  * a valid mapping and a zero value if all of the categories are valid.
790  *
791  */
792 static int cipso_v4_map_cat_rbm_valid(const struct cipso_v4_doi *doi_def,
793                                       const unsigned char *bitmap,
794                                       u32 bitmap_len)
795 {
796         int cat = -1;
797         u32 bitmap_len_bits = bitmap_len * 8;
798         u32 cipso_cat_size;
799         u32 *cipso_array;
800
801         switch (doi_def->type) {
802         case CIPSO_V4_MAP_PASS:
803                 return 0;
804         case CIPSO_V4_MAP_STD:
805                 cipso_cat_size = doi_def->map.std->cat.cipso_size;
806                 cipso_array = doi_def->map.std->cat.cipso;
807                 for (;;) {
808                         cat = cipso_v4_bitmap_walk(bitmap,
809                                                    bitmap_len_bits,
810                                                    cat + 1,
811                                                    1);
812                         if (cat < 0)
813                                 break;
814                         if (cat >= cipso_cat_size ||
815                             cipso_array[cat] >= CIPSO_V4_INV_CAT)
816                                 return -EFAULT;
817                 }
818
819                 if (cat == -1)
820                         return 0;
821                 break;
822         }
823
824         return -EFAULT;
825 }
826
827 /**
828  * cipso_v4_map_cat_rbm_hton - Perform a category mapping from host to network
829  * @doi_def: the DOI definition
830  * @secattr: the security attributes
831  * @net_cat: the zero'd out category bitmap in network/CIPSO format
832  * @net_cat_len: the length of the CIPSO bitmap in bytes
833  *
834  * Description:
835  * Perform a label mapping to translate a local MLS category bitmap to the
836  * correct CIPSO bitmap using the given DOI definition.  Returns the minimum
837  * size in bytes of the network bitmap on success, negative values otherwise.
838  *
839  */
840 static int cipso_v4_map_cat_rbm_hton(const struct cipso_v4_doi *doi_def,
841                                      const struct netlbl_lsm_secattr *secattr,
842                                      unsigned char *net_cat,
843                                      u32 net_cat_len)
844 {
845         int host_spot = -1;
846         u32 net_spot = CIPSO_V4_INV_CAT;
847         u32 net_spot_max = 0;
848         u32 net_clen_bits = net_cat_len * 8;
849         u32 host_cat_size = 0;
850         u32 *host_cat_array = NULL;
851
852         if (doi_def->type == CIPSO_V4_MAP_STD) {
853                 host_cat_size = doi_def->map.std->cat.local_size;
854                 host_cat_array = doi_def->map.std->cat.local;
855         }
856
857         for (;;) {
858                 host_spot = netlbl_secattr_catmap_walk(secattr->mls_cat,
859                                                        host_spot + 1);
860                 if (host_spot < 0)
861                         break;
862
863                 switch (doi_def->type) {
864                 case CIPSO_V4_MAP_PASS:
865                         net_spot = host_spot;
866                         break;
867                 case CIPSO_V4_MAP_STD:
868                         if (host_spot >= host_cat_size)
869                                 return -EPERM;
870                         net_spot = host_cat_array[host_spot];
871                         if (net_spot >= CIPSO_V4_INV_CAT)
872                                 return -EPERM;
873                         break;
874                 }
875                 if (net_spot >= net_clen_bits)
876                         return -ENOSPC;
877                 cipso_v4_bitmap_setbit(net_cat, net_spot, 1);
878
879                 if (net_spot > net_spot_max)
880                         net_spot_max = net_spot;
881         }
882
883         if (++net_spot_max % 8)
884                 return net_spot_max / 8 + 1;
885         return net_spot_max / 8;
886 }
887
888 /**
889  * cipso_v4_map_cat_rbm_ntoh - Perform a category mapping from network to host
890  * @doi_def: the DOI definition
891  * @net_cat: the category bitmap in network/CIPSO format
892  * @net_cat_len: the length of the CIPSO bitmap in bytes
893  * @secattr: the security attributes
894  *
895  * Description:
896  * Perform a label mapping to translate a CIPSO bitmap to the correct local
897  * MLS category bitmap using the given DOI definition.  Returns zero on
898  * success, negative values on failure.
899  *
900  */
901 static int cipso_v4_map_cat_rbm_ntoh(const struct cipso_v4_doi *doi_def,
902                                      const unsigned char *net_cat,
903                                      u32 net_cat_len,
904                                      struct netlbl_lsm_secattr *secattr)
905 {
906         int ret_val;
907         int net_spot = -1;
908         u32 host_spot = CIPSO_V4_INV_CAT;
909         u32 net_clen_bits = net_cat_len * 8;
910         u32 net_cat_size = 0;
911         u32 *net_cat_array = NULL;
912
913         if (doi_def->type == CIPSO_V4_MAP_STD) {
914                 net_cat_size = doi_def->map.std->cat.cipso_size;
915                 net_cat_array = doi_def->map.std->cat.cipso;
916         }
917
918         for (;;) {
919                 net_spot = cipso_v4_bitmap_walk(net_cat,
920                                                 net_clen_bits,
921                                                 net_spot + 1,
922                                                 1);
923                 if (net_spot < 0) {
924                         if (net_spot == -2)
925                                 return -EFAULT;
926                         return 0;
927                 }
928
929                 switch (doi_def->type) {
930                 case CIPSO_V4_MAP_PASS:
931                         host_spot = net_spot;
932                         break;
933                 case CIPSO_V4_MAP_STD:
934                         if (net_spot >= net_cat_size)
935                                 return -EPERM;
936                         host_spot = net_cat_array[net_spot];
937                         if (host_spot >= CIPSO_V4_INV_CAT)
938                                 return -EPERM;
939                         break;
940                 }
941                 ret_val = netlbl_secattr_catmap_setbit(secattr->mls_cat,
942                                                        host_spot,
943                                                        GFP_ATOMIC);
944                 if (ret_val != 0)
945                         return ret_val;
946         }
947
948         return -EINVAL;
949 }
950
951 /**
952  * cipso_v4_map_cat_enum_valid - Checks to see if the categories are valid
953  * @doi_def: the DOI definition
954  * @enumcat: category list
955  * @enumcat_len: length of the category list in bytes
956  *
957  * Description:
958  * Checks the given categories against the given DOI definition and returns a
959  * negative value if any of the categories do not have a valid mapping and a
960  * zero value if all of the categories are valid.
961  *
962  */
963 static int cipso_v4_map_cat_enum_valid(const struct cipso_v4_doi *doi_def,
964                                        const unsigned char *enumcat,
965                                        u32 enumcat_len)
966 {
967         u16 cat;
968         int cat_prev = -1;
969         u32 iter;
970
971         if (doi_def->type != CIPSO_V4_MAP_PASS || enumcat_len & 0x01)
972                 return -EFAULT;
973
974         for (iter = 0; iter < enumcat_len; iter += 2) {
975                 cat = ntohs(*((__be16 *)&enumcat[iter]));
976                 if (cat <= cat_prev)
977                         return -EFAULT;
978                 cat_prev = cat;
979         }
980
981         return 0;
982 }
983
984 /**
985  * cipso_v4_map_cat_enum_hton - Perform a category mapping from host to network
986  * @doi_def: the DOI definition
987  * @secattr: the security attributes
988  * @net_cat: the zero'd out category list in network/CIPSO format
989  * @net_cat_len: the length of the CIPSO category list in bytes
990  *
991  * Description:
992  * Perform a label mapping to translate a local MLS category bitmap to the
993  * correct CIPSO category list using the given DOI definition.   Returns the
994  * size in bytes of the network category bitmap on success, negative values
995  * otherwise.
996  *
997  */
998 static int cipso_v4_map_cat_enum_hton(const struct cipso_v4_doi *doi_def,
999                                       const struct netlbl_lsm_secattr *secattr,
1000                                       unsigned char *net_cat,
1001                                       u32 net_cat_len)
1002 {
1003         int cat = -1;
1004         u32 cat_iter = 0;
1005
1006         for (;;) {
1007                 cat = netlbl_secattr_catmap_walk(secattr->mls_cat, cat + 1);
1008                 if (cat < 0)
1009                         break;
1010                 if ((cat_iter + 2) > net_cat_len)
1011                         return -ENOSPC;
1012
1013                 *((__be16 *)&net_cat[cat_iter]) = htons(cat);
1014                 cat_iter += 2;
1015         }
1016
1017         return cat_iter;
1018 }
1019
1020 /**
1021  * cipso_v4_map_cat_enum_ntoh - Perform a category mapping from network to host
1022  * @doi_def: the DOI definition
1023  * @net_cat: the category list in network/CIPSO format
1024  * @net_cat_len: the length of the CIPSO bitmap in bytes
1025  * @secattr: the security attributes
1026  *
1027  * Description:
1028  * Perform a label mapping to translate a CIPSO category list to the correct
1029  * local MLS category bitmap using the given DOI definition.  Returns zero on
1030  * success, negative values on failure.
1031  *
1032  */
1033 static int cipso_v4_map_cat_enum_ntoh(const struct cipso_v4_doi *doi_def,
1034                                       const unsigned char *net_cat,
1035                                       u32 net_cat_len,
1036                                       struct netlbl_lsm_secattr *secattr)
1037 {
1038         int ret_val;
1039         u32 iter;
1040
1041         for (iter = 0; iter < net_cat_len; iter += 2) {
1042                 ret_val = netlbl_secattr_catmap_setbit(secattr->mls_cat,
1043                                             ntohs(*((__be16 *)&net_cat[iter])),
1044                                             GFP_ATOMIC);
1045                 if (ret_val != 0)
1046                         return ret_val;
1047         }
1048
1049         return 0;
1050 }
1051
1052 /**
1053  * cipso_v4_map_cat_rng_valid - Checks to see if the categories are valid
1054  * @doi_def: the DOI definition
1055  * @rngcat: category list
1056  * @rngcat_len: length of the category list in bytes
1057  *
1058  * Description:
1059  * Checks the given categories against the given DOI definition and returns a
1060  * negative value if any of the categories do not have a valid mapping and a
1061  * zero value if all of the categories are valid.
1062  *
1063  */
1064 static int cipso_v4_map_cat_rng_valid(const struct cipso_v4_doi *doi_def,
1065                                       const unsigned char *rngcat,
1066                                       u32 rngcat_len)
1067 {
1068         u16 cat_high;
1069         u16 cat_low;
1070         u32 cat_prev = CIPSO_V4_MAX_REM_CATS + 1;
1071         u32 iter;
1072
1073         if (doi_def->type != CIPSO_V4_MAP_PASS || rngcat_len & 0x01)
1074                 return -EFAULT;
1075
1076         for (iter = 0; iter < rngcat_len; iter += 4) {
1077                 cat_high = ntohs(*((__be16 *)&rngcat[iter]));
1078                 if ((iter + 4) <= rngcat_len)
1079                         cat_low = ntohs(*((__be16 *)&rngcat[iter + 2]));
1080                 else
1081                         cat_low = 0;
1082
1083                 if (cat_high > cat_prev)
1084                         return -EFAULT;
1085
1086                 cat_prev = cat_low;
1087         }
1088
1089         return 0;
1090 }
1091
1092 /**
1093  * cipso_v4_map_cat_rng_hton - Perform a category mapping from host to network
1094  * @doi_def: the DOI definition
1095  * @secattr: the security attributes
1096  * @net_cat: the zero'd out category list in network/CIPSO format
1097  * @net_cat_len: the length of the CIPSO category list in bytes
1098  *
1099  * Description:
1100  * Perform a label mapping to translate a local MLS category bitmap to the
1101  * correct CIPSO category list using the given DOI definition.   Returns the
1102  * size in bytes of the network category bitmap on success, negative values
1103  * otherwise.
1104  *
1105  */
1106 static int cipso_v4_map_cat_rng_hton(const struct cipso_v4_doi *doi_def,
1107                                      const struct netlbl_lsm_secattr *secattr,
1108                                      unsigned char *net_cat,
1109                                      u32 net_cat_len)
1110 {
1111         /* The constant '16' is not random, it is the maximum number of
1112          * high/low category range pairs as permitted by the CIPSO draft based
1113          * on a maximum IPv4 header length of 60 bytes - the BUG_ON() assertion
1114          * does a sanity check to make sure we don't overflow the array. */
1115         int iter = -1;
1116         u16 array[16];
1117         u32 array_cnt = 0;
1118         u32 cat_size = 0;
1119
1120         BUG_ON(net_cat_len > 30);
1121
1122         for (;;) {
1123                 iter = netlbl_secattr_catmap_walk(secattr->mls_cat, iter + 1);
1124                 if (iter < 0)
1125                         break;
1126                 cat_size += (iter == 0 ? 0 : sizeof(u16));
1127                 if (cat_size > net_cat_len)
1128                         return -ENOSPC;
1129                 array[array_cnt++] = iter;
1130
1131                 iter = netlbl_secattr_catmap_walk_rng(secattr->mls_cat, iter);
1132                 if (iter < 0)
1133                         return -EFAULT;
1134                 cat_size += sizeof(u16);
1135                 if (cat_size > net_cat_len)
1136                         return -ENOSPC;
1137                 array[array_cnt++] = iter;
1138         }
1139
1140         for (iter = 0; array_cnt > 0;) {
1141                 *((__be16 *)&net_cat[iter]) = htons(array[--array_cnt]);
1142                 iter += 2;
1143                 array_cnt--;
1144                 if (array[array_cnt] != 0) {
1145                         *((__be16 *)&net_cat[iter]) = htons(array[array_cnt]);
1146                         iter += 2;
1147                 }
1148         }
1149
1150         return cat_size;
1151 }
1152
1153 /**
1154  * cipso_v4_map_cat_rng_ntoh - Perform a category mapping from network to host
1155  * @doi_def: the DOI definition
1156  * @net_cat: the category list in network/CIPSO format
1157  * @net_cat_len: the length of the CIPSO bitmap in bytes
1158  * @secattr: the security attributes
1159  *
1160  * Description:
1161  * Perform a label mapping to translate a CIPSO category list to the correct
1162  * local MLS category bitmap using the given DOI definition.  Returns zero on
1163  * success, negative values on failure.
1164  *
1165  */
1166 static int cipso_v4_map_cat_rng_ntoh(const struct cipso_v4_doi *doi_def,
1167                                      const unsigned char *net_cat,
1168                                      u32 net_cat_len,
1169                                      struct netlbl_lsm_secattr *secattr)
1170 {
1171         int ret_val;
1172         u32 net_iter;
1173         u16 cat_low;
1174         u16 cat_high;
1175
1176         for(net_iter = 0; net_iter < net_cat_len; net_iter += 4) {
1177                 cat_high = ntohs(*((__be16 *)&net_cat[net_iter]));
1178                 if ((net_iter + 4) <= net_cat_len)
1179                         cat_low = ntohs(*((__be16 *)&net_cat[net_iter + 2]));
1180                 else
1181                         cat_low = 0;
1182
1183                 ret_val = netlbl_secattr_catmap_setrng(secattr->mls_cat,
1184                                                        cat_low,
1185                                                        cat_high,
1186                                                        GFP_ATOMIC);
1187                 if (ret_val != 0)
1188                         return ret_val;
1189         }
1190
1191         return 0;
1192 }
1193
1194 /*
1195  * Protocol Handling Functions
1196  */
1197
1198 #define CIPSO_V4_OPT_LEN_MAX          40
1199 #define CIPSO_V4_HDR_LEN              6
1200
1201 /**
1202  * cipso_v4_gentag_hdr - Generate a CIPSO option header
1203  * @doi_def: the DOI definition
1204  * @len: the total tag length in bytes, not including this header
1205  * @buf: the CIPSO option buffer
1206  *
1207  * Description:
1208  * Write a CIPSO header into the beginning of @buffer.
1209  *
1210  */
1211 static void cipso_v4_gentag_hdr(const struct cipso_v4_doi *doi_def,
1212                                 unsigned char *buf,
1213                                 u32 len)
1214 {
1215         buf[0] = IPOPT_CIPSO;
1216         buf[1] = CIPSO_V4_HDR_LEN + len;
1217         *(__be32 *)&buf[2] = htonl(doi_def->doi);
1218 }
1219
1220 /**
1221  * cipso_v4_gentag_rbm - Generate a CIPSO restricted bitmap tag (type #1)
1222  * @doi_def: the DOI definition
1223  * @secattr: the security attributes
1224  * @buffer: the option buffer
1225  * @buffer_len: length of buffer in bytes
1226  *
1227  * Description:
1228  * Generate a CIPSO option using the restricted bitmap tag, tag type #1.  The
1229  * actual buffer length may be larger than the indicated size due to
1230  * translation between host and network category bitmaps.  Returns the size of
1231  * the tag on success, negative values on failure.
1232  *
1233  */
1234 static int cipso_v4_gentag_rbm(const struct cipso_v4_doi *doi_def,
1235                                const struct netlbl_lsm_secattr *secattr,
1236                                unsigned char *buffer,
1237                                u32 buffer_len)
1238 {
1239         int ret_val;
1240         u32 tag_len;
1241         u32 level;
1242
1243         if ((secattr->flags & NETLBL_SECATTR_MLS_LVL) == 0)
1244                 return -EPERM;
1245
1246         ret_val = cipso_v4_map_lvl_hton(doi_def, secattr->mls_lvl, &level);
1247         if (ret_val != 0)
1248                 return ret_val;
1249
1250         if (secattr->flags & NETLBL_SECATTR_MLS_CAT) {
1251                 ret_val = cipso_v4_map_cat_rbm_hton(doi_def,
1252                                                     secattr,
1253                                                     &buffer[4],
1254                                                     buffer_len - 4);
1255                 if (ret_val < 0)
1256                         return ret_val;
1257
1258                 /* This will send packets using the "optimized" format when
1259                  * possibile as specified in  section 3.4.2.6 of the
1260                  * CIPSO draft. */
1261                 if (cipso_v4_rbm_optfmt && ret_val > 0 && ret_val <= 10)
1262                         tag_len = 14;
1263                 else
1264                         tag_len = 4 + ret_val;
1265         } else
1266                 tag_len = 4;
1267
1268         buffer[0] = 0x01;
1269         buffer[1] = tag_len;
1270         buffer[3] = level;
1271
1272         return tag_len;
1273 }
1274
1275 /**
1276  * cipso_v4_parsetag_rbm - Parse a CIPSO restricted bitmap tag
1277  * @doi_def: the DOI definition
1278  * @tag: the CIPSO tag
1279  * @secattr: the security attributes
1280  *
1281  * Description:
1282  * Parse a CIPSO restricted bitmap tag (tag type #1) and return the security
1283  * attributes in @secattr.  Return zero on success, negatives values on
1284  * failure.
1285  *
1286  */
1287 static int cipso_v4_parsetag_rbm(const struct cipso_v4_doi *doi_def,
1288                                  const unsigned char *tag,
1289                                  struct netlbl_lsm_secattr *secattr)
1290 {
1291         int ret_val;
1292         u8 tag_len = tag[1];
1293         u32 level;
1294
1295         ret_val = cipso_v4_map_lvl_ntoh(doi_def, tag[3], &level);
1296         if (ret_val != 0)
1297                 return ret_val;
1298         secattr->mls_lvl = level;
1299         secattr->flags |= NETLBL_SECATTR_MLS_LVL;
1300
1301         if (tag_len > 4) {
1302                 secattr->mls_cat = netlbl_secattr_catmap_alloc(GFP_ATOMIC);
1303                 if (secattr->mls_cat == NULL)
1304                         return -ENOMEM;
1305
1306                 ret_val = cipso_v4_map_cat_rbm_ntoh(doi_def,
1307                                                     &tag[4],
1308                                                     tag_len - 4,
1309                                                     secattr);
1310                 if (ret_val != 0) {
1311                         netlbl_secattr_catmap_free(secattr->mls_cat);
1312                         return ret_val;
1313                 }
1314
1315                 secattr->flags |= NETLBL_SECATTR_MLS_CAT;
1316         }
1317
1318         return 0;
1319 }
1320
1321 /**
1322  * cipso_v4_gentag_enum - Generate a CIPSO enumerated tag (type #2)
1323  * @doi_def: the DOI definition
1324  * @secattr: the security attributes
1325  * @buffer: the option buffer
1326  * @buffer_len: length of buffer in bytes
1327  *
1328  * Description:
1329  * Generate a CIPSO option using the enumerated tag, tag type #2.  Returns the
1330  * size of the tag on success, negative values on failure.
1331  *
1332  */
1333 static int cipso_v4_gentag_enum(const struct cipso_v4_doi *doi_def,
1334                                 const struct netlbl_lsm_secattr *secattr,
1335                                 unsigned char *buffer,
1336                                 u32 buffer_len)
1337 {
1338         int ret_val;
1339         u32 tag_len;
1340         u32 level;
1341
1342         if (!(secattr->flags & NETLBL_SECATTR_MLS_LVL))
1343                 return -EPERM;
1344
1345         ret_val = cipso_v4_map_lvl_hton(doi_def, secattr->mls_lvl, &level);
1346         if (ret_val != 0)
1347                 return ret_val;
1348
1349         if (secattr->flags & NETLBL_SECATTR_MLS_CAT) {
1350                 ret_val = cipso_v4_map_cat_enum_hton(doi_def,
1351                                                      secattr,
1352                                                      &buffer[4],
1353                                                      buffer_len - 4);
1354                 if (ret_val < 0)
1355                         return ret_val;
1356
1357                 tag_len = 4 + ret_val;
1358         } else
1359                 tag_len = 4;
1360
1361         buffer[0] = 0x02;
1362         buffer[1] = tag_len;
1363         buffer[3] = level;
1364
1365         return tag_len;
1366 }
1367
1368 /**
1369  * cipso_v4_parsetag_enum - Parse a CIPSO enumerated tag
1370  * @doi_def: the DOI definition
1371  * @tag: the CIPSO tag
1372  * @secattr: the security attributes
1373  *
1374  * Description:
1375  * Parse a CIPSO enumerated tag (tag type #2) and return the security
1376  * attributes in @secattr.  Return zero on success, negatives values on
1377  * failure.
1378  *
1379  */
1380 static int cipso_v4_parsetag_enum(const struct cipso_v4_doi *doi_def,
1381                                   const unsigned char *tag,
1382                                   struct netlbl_lsm_secattr *secattr)
1383 {
1384         int ret_val;
1385         u8 tag_len = tag[1];
1386         u32 level;
1387
1388         ret_val = cipso_v4_map_lvl_ntoh(doi_def, tag[3], &level);
1389         if (ret_val != 0)
1390                 return ret_val;
1391         secattr->mls_lvl = level;
1392         secattr->flags |= NETLBL_SECATTR_MLS_LVL;
1393
1394         if (tag_len > 4) {
1395                 secattr->mls_cat = netlbl_secattr_catmap_alloc(GFP_ATOMIC);
1396                 if (secattr->mls_cat == NULL)
1397                         return -ENOMEM;
1398
1399                 ret_val = cipso_v4_map_cat_enum_ntoh(doi_def,
1400                                                      &tag[4],
1401                                                      tag_len - 4,
1402                                                      secattr);
1403                 if (ret_val != 0) {
1404                         netlbl_secattr_catmap_free(secattr->mls_cat);
1405                         return ret_val;
1406                 }
1407
1408                 secattr->flags |= NETLBL_SECATTR_MLS_CAT;
1409         }
1410
1411         return 0;
1412 }
1413
1414 /**
1415  * cipso_v4_gentag_rng - Generate a CIPSO ranged tag (type #5)
1416  * @doi_def: the DOI definition
1417  * @secattr: the security attributes
1418  * @buffer: the option buffer
1419  * @buffer_len: length of buffer in bytes
1420  *
1421  * Description:
1422  * Generate a CIPSO option using the ranged tag, tag type #5.  Returns the
1423  * size of the tag on success, negative values on failure.
1424  *
1425  */
1426 static int cipso_v4_gentag_rng(const struct cipso_v4_doi *doi_def,
1427                                const struct netlbl_lsm_secattr *secattr,
1428                                unsigned char *buffer,
1429                                u32 buffer_len)
1430 {
1431         int ret_val;
1432         u32 tag_len;
1433         u32 level;
1434
1435         if (!(secattr->flags & NETLBL_SECATTR_MLS_LVL))
1436                 return -EPERM;
1437
1438         ret_val = cipso_v4_map_lvl_hton(doi_def, secattr->mls_lvl, &level);
1439         if (ret_val != 0)
1440                 return ret_val;
1441
1442         if (secattr->flags & NETLBL_SECATTR_MLS_CAT) {
1443                 ret_val = cipso_v4_map_cat_rng_hton(doi_def,
1444                                                     secattr,
1445                                                     &buffer[4],
1446                                                     buffer_len - 4);
1447                 if (ret_val < 0)
1448                         return ret_val;
1449
1450                 tag_len = 4 + ret_val;
1451         } else
1452                 tag_len = 4;
1453
1454         buffer[0] = 0x05;
1455         buffer[1] = tag_len;
1456         buffer[3] = level;
1457
1458         return tag_len;
1459 }
1460
1461 /**
1462  * cipso_v4_parsetag_rng - Parse a CIPSO ranged tag
1463  * @doi_def: the DOI definition
1464  * @tag: the CIPSO tag
1465  * @secattr: the security attributes
1466  *
1467  * Description:
1468  * Parse a CIPSO ranged tag (tag type #5) and return the security attributes
1469  * in @secattr.  Return zero on success, negatives values on failure.
1470  *
1471  */
1472 static int cipso_v4_parsetag_rng(const struct cipso_v4_doi *doi_def,
1473                                  const unsigned char *tag,
1474                                  struct netlbl_lsm_secattr *secattr)
1475 {
1476         int ret_val;
1477         u8 tag_len = tag[1];
1478         u32 level;
1479
1480         ret_val = cipso_v4_map_lvl_ntoh(doi_def, tag[3], &level);
1481         if (ret_val != 0)
1482                 return ret_val;
1483         secattr->mls_lvl = level;
1484         secattr->flags |= NETLBL_SECATTR_MLS_LVL;
1485
1486         if (tag_len > 4) {
1487                 secattr->mls_cat = netlbl_secattr_catmap_alloc(GFP_ATOMIC);
1488                 if (secattr->mls_cat == NULL)
1489                         return -ENOMEM;
1490
1491                 ret_val = cipso_v4_map_cat_rng_ntoh(doi_def,
1492                                                     &tag[4],
1493                                                     tag_len - 4,
1494                                                     secattr);
1495                 if (ret_val != 0) {
1496                         netlbl_secattr_catmap_free(secattr->mls_cat);
1497                         return ret_val;
1498                 }
1499
1500                 secattr->flags |= NETLBL_SECATTR_MLS_CAT;
1501         }
1502
1503         return 0;
1504 }
1505
1506 /**
1507  * cipso_v4_validate - Validate a CIPSO option
1508  * @option: the start of the option, on error it is set to point to the error
1509  *
1510  * Description:
1511  * This routine is called to validate a CIPSO option, it checks all of the
1512  * fields to ensure that they are at least valid, see the draft snippet below
1513  * for details.  If the option is valid then a zero value is returned and
1514  * the value of @option is unchanged.  If the option is invalid then a
1515  * non-zero value is returned and @option is adjusted to point to the
1516  * offending portion of the option.  From the IETF draft ...
1517  *
1518  *  "If any field within the CIPSO options, such as the DOI identifier, is not
1519  *   recognized the IP datagram is discarded and an ICMP 'parameter problem'
1520  *   (type 12) is generated and returned.  The ICMP code field is set to 'bad
1521  *   parameter' (code 0) and the pointer is set to the start of the CIPSO field
1522  *   that is unrecognized."
1523  *
1524  */
1525 int cipso_v4_validate(unsigned char **option)
1526 {
1527         unsigned char *opt = *option;
1528         unsigned char *tag;
1529         unsigned char opt_iter;
1530         unsigned char err_offset = 0;
1531         u8 opt_len;
1532         u8 tag_len;
1533         struct cipso_v4_doi *doi_def = NULL;
1534         u32 tag_iter;
1535
1536         /* caller already checks for length values that are too large */
1537         opt_len = opt[1];
1538         if (opt_len < 8) {
1539                 err_offset = 1;
1540                 goto validate_return;
1541         }
1542
1543         rcu_read_lock();
1544         doi_def = cipso_v4_doi_search(ntohl(*((__be32 *)&opt[2])));
1545         if (doi_def == NULL) {
1546                 err_offset = 2;
1547                 goto validate_return_locked;
1548         }
1549
1550         opt_iter = 6;
1551         tag = opt + opt_iter;
1552         while (opt_iter < opt_len) {
1553                 for (tag_iter = 0; doi_def->tags[tag_iter] != tag[0];)
1554                         if (doi_def->tags[tag_iter] == CIPSO_V4_TAG_INVALID ||
1555                             ++tag_iter == CIPSO_V4_TAG_MAXCNT) {
1556                                 err_offset = opt_iter;
1557                                 goto validate_return_locked;
1558                         }
1559
1560                 tag_len = tag[1];
1561                 if (tag_len > (opt_len - opt_iter)) {
1562                         err_offset = opt_iter + 1;
1563                         goto validate_return_locked;
1564                 }
1565
1566                 switch (tag[0]) {
1567                 case CIPSO_V4_TAG_RBITMAP:
1568                         if (tag_len < 4) {
1569                                 err_offset = opt_iter + 1;
1570                                 goto validate_return_locked;
1571                         }
1572
1573                         /* We are already going to do all the verification
1574                          * necessary at the socket layer so from our point of
1575                          * view it is safe to turn these checks off (and less
1576                          * work), however, the CIPSO draft says we should do
1577                          * all the CIPSO validations here but it doesn't
1578                          * really specify _exactly_ what we need to validate
1579                          * ... so, just make it a sysctl tunable. */
1580                         if (cipso_v4_rbm_strictvalid) {
1581                                 if (cipso_v4_map_lvl_valid(doi_def,
1582                                                            tag[3]) < 0) {
1583                                         err_offset = opt_iter + 3;
1584                                         goto validate_return_locked;
1585                                 }
1586                                 if (tag_len > 4 &&
1587                                     cipso_v4_map_cat_rbm_valid(doi_def,
1588                                                             &tag[4],
1589                                                             tag_len - 4) < 0) {
1590                                         err_offset = opt_iter + 4;
1591                                         goto validate_return_locked;
1592                                 }
1593                         }
1594                         break;
1595                 case CIPSO_V4_TAG_ENUM:
1596                         if (tag_len < 4) {
1597                                 err_offset = opt_iter + 1;
1598                                 goto validate_return_locked;
1599                         }
1600
1601                         if (cipso_v4_map_lvl_valid(doi_def,
1602                                                    tag[3]) < 0) {
1603                                 err_offset = opt_iter + 3;
1604                                 goto validate_return_locked;
1605                         }
1606                         if (tag_len > 4 &&
1607                             cipso_v4_map_cat_enum_valid(doi_def,
1608                                                         &tag[4],
1609                                                         tag_len - 4) < 0) {
1610                                 err_offset = opt_iter + 4;
1611                                 goto validate_return_locked;
1612                         }
1613                         break;
1614                 case CIPSO_V4_TAG_RANGE:
1615                         if (tag_len < 4) {
1616                                 err_offset = opt_iter + 1;
1617                                 goto validate_return_locked;
1618                         }
1619
1620                         if (cipso_v4_map_lvl_valid(doi_def,
1621                                                    tag[3]) < 0) {
1622                                 err_offset = opt_iter + 3;
1623                                 goto validate_return_locked;
1624                         }
1625                         if (tag_len > 4 &&
1626                             cipso_v4_map_cat_rng_valid(doi_def,
1627                                                        &tag[4],
1628                                                        tag_len - 4) < 0) {
1629                                 err_offset = opt_iter + 4;
1630                                 goto validate_return_locked;
1631                         }
1632                         break;
1633                 default:
1634                         err_offset = opt_iter;
1635                         goto validate_return_locked;
1636                 }
1637
1638                 tag += tag_len;
1639                 opt_iter += tag_len;
1640         }
1641
1642 validate_return_locked:
1643         rcu_read_unlock();
1644 validate_return:
1645         *option = opt + err_offset;
1646         return err_offset;
1647 }
1648
1649 /**
1650  * cipso_v4_error - Send the correct reponse for a bad packet
1651  * @skb: the packet
1652  * @error: the error code
1653  * @gateway: CIPSO gateway flag
1654  *
1655  * Description:
1656  * Based on the error code given in @error, send an ICMP error message back to
1657  * the originating host.  From the IETF draft ...
1658  *
1659  *  "If the contents of the CIPSO [option] are valid but the security label is
1660  *   outside of the configured host or port label range, the datagram is
1661  *   discarded and an ICMP 'destination unreachable' (type 3) is generated and
1662  *   returned.  The code field of the ICMP is set to 'communication with
1663  *   destination network administratively prohibited' (code 9) or to
1664  *   'communication with destination host administratively prohibited'
1665  *   (code 10).  The value of the code is dependent on whether the originator
1666  *   of the ICMP message is acting as a CIPSO host or a CIPSO gateway.  The
1667  *   recipient of the ICMP message MUST be able to handle either value.  The
1668  *   same procedure is performed if a CIPSO [option] can not be added to an
1669  *   IP packet because it is too large to fit in the IP options area."
1670  *
1671  *  "If the error is triggered by receipt of an ICMP message, the message is
1672  *   discarded and no response is permitted (consistent with general ICMP
1673  *   processing rules)."
1674  *
1675  */
1676 void cipso_v4_error(struct sk_buff *skb, int error, u32 gateway)
1677 {
1678         if (skb->nh.iph->protocol == IPPROTO_ICMP || error != -EACCES)
1679                 return;
1680
1681         if (gateway)
1682                 icmp_send(skb, ICMP_DEST_UNREACH, ICMP_NET_ANO, 0);
1683         else
1684                 icmp_send(skb, ICMP_DEST_UNREACH, ICMP_HOST_ANO, 0);
1685 }
1686
1687 /**
1688  * cipso_v4_socket_setattr - Add a CIPSO option to a socket
1689  * @sock: the socket
1690  * @doi_def: the CIPSO DOI to use
1691  * @secattr: the specific security attributes of the socket
1692  *
1693  * Description:
1694  * Set the CIPSO option on the given socket using the DOI definition and
1695  * security attributes passed to the function.  This function requires
1696  * exclusive access to @sock->sk, which means it either needs to be in the
1697  * process of being created or locked via lock_sock(sock->sk).  Returns zero on
1698  * success and negative values on failure.
1699  *
1700  */
1701 int cipso_v4_socket_setattr(const struct socket *sock,
1702                             const struct cipso_v4_doi *doi_def,
1703                             const struct netlbl_lsm_secattr *secattr)
1704 {
1705         int ret_val = -EPERM;
1706         u32 iter;
1707         unsigned char *buf;
1708         u32 buf_len = 0;
1709         u32 opt_len;
1710         struct ip_options *opt = NULL;
1711         struct sock *sk;
1712         struct inet_sock *sk_inet;
1713         struct inet_connection_sock *sk_conn;
1714
1715         /* In the case of sock_create_lite(), the sock->sk field is not
1716          * defined yet but it is not a problem as the only users of these
1717          * "lite" PF_INET sockets are functions which do an accept() call
1718          * afterwards so we will label the socket as part of the accept(). */
1719         sk = sock->sk;
1720         if (sk == NULL)
1721                 return 0;
1722
1723         /* We allocate the maximum CIPSO option size here so we are probably
1724          * being a little wasteful, but it makes our life _much_ easier later
1725          * on and after all we are only talking about 40 bytes. */
1726         buf_len = CIPSO_V4_OPT_LEN_MAX;
1727         buf = kmalloc(buf_len, GFP_ATOMIC);
1728         if (buf == NULL) {
1729                 ret_val = -ENOMEM;
1730                 goto socket_setattr_failure;
1731         }
1732
1733         /* XXX - This code assumes only one tag per CIPSO option which isn't
1734          * really a good assumption to make but since we only support the MAC
1735          * tags right now it is a safe assumption. */
1736         iter = 0;
1737         do {
1738                 memset(buf, 0, buf_len);
1739                 switch (doi_def->tags[iter]) {
1740                 case CIPSO_V4_TAG_RBITMAP:
1741                         ret_val = cipso_v4_gentag_rbm(doi_def,
1742                                                    secattr,
1743                                                    &buf[CIPSO_V4_HDR_LEN],
1744                                                    buf_len - CIPSO_V4_HDR_LEN);
1745                         break;
1746                 case CIPSO_V4_TAG_ENUM:
1747                         ret_val = cipso_v4_gentag_enum(doi_def,
1748                                                    secattr,
1749                                                    &buf[CIPSO_V4_HDR_LEN],
1750                                                    buf_len - CIPSO_V4_HDR_LEN);
1751                         break;
1752                 case CIPSO_V4_TAG_RANGE:
1753                         ret_val = cipso_v4_gentag_rng(doi_def,
1754                                                    secattr,
1755                                                    &buf[CIPSO_V4_HDR_LEN],
1756                                                    buf_len - CIPSO_V4_HDR_LEN);
1757                         break;
1758                 default:
1759                         ret_val = -EPERM;
1760                         goto socket_setattr_failure;
1761                 }
1762
1763                 iter++;
1764         } while (ret_val < 0 &&
1765                  iter < CIPSO_V4_TAG_MAXCNT &&
1766                  doi_def->tags[iter] != CIPSO_V4_TAG_INVALID);
1767         if (ret_val < 0)
1768                 goto socket_setattr_failure;
1769         cipso_v4_gentag_hdr(doi_def, buf, ret_val);
1770         buf_len = CIPSO_V4_HDR_LEN + ret_val;
1771
1772         /* We can't use ip_options_get() directly because it makes a call to
1773          * ip_options_get_alloc() which allocates memory with GFP_KERNEL and
1774          * we won't always have CAP_NET_RAW even though we _always_ want to
1775          * set the IPOPT_CIPSO option. */
1776         opt_len = (buf_len + 3) & ~3;
1777         opt = kzalloc(sizeof(*opt) + opt_len, GFP_ATOMIC);
1778         if (opt == NULL) {
1779                 ret_val = -ENOMEM;
1780                 goto socket_setattr_failure;
1781         }
1782         memcpy(opt->__data, buf, buf_len);
1783         opt->optlen = opt_len;
1784         opt->is_data = 1;
1785         opt->cipso = sizeof(struct iphdr);
1786         kfree(buf);
1787         buf = NULL;
1788
1789         sk_inet = inet_sk(sk);
1790         if (sk_inet->is_icsk) {
1791                 sk_conn = inet_csk(sk);
1792                 if (sk_inet->opt)
1793                         sk_conn->icsk_ext_hdr_len -= sk_inet->opt->optlen;
1794                 sk_conn->icsk_ext_hdr_len += opt->optlen;
1795                 sk_conn->icsk_sync_mss(sk, sk_conn->icsk_pmtu_cookie);
1796         }
1797         opt = xchg(&sk_inet->opt, opt);
1798         kfree(opt);
1799
1800         return 0;
1801
1802 socket_setattr_failure:
1803         kfree(buf);
1804         kfree(opt);
1805         return ret_val;
1806 }
1807
1808 /**
1809  * cipso_v4_sock_getattr - Get the security attributes from a sock
1810  * @sk: the sock
1811  * @secattr: the security attributes
1812  *
1813  * Description:
1814  * Query @sk to see if there is a CIPSO option attached to the sock and if
1815  * there is return the CIPSO security attributes in @secattr.  This function
1816  * requires that @sk be locked, or privately held, but it does not do any
1817  * locking itself.  Returns zero on success and negative values on failure.
1818  *
1819  */
1820 int cipso_v4_sock_getattr(struct sock *sk, struct netlbl_lsm_secattr *secattr)
1821 {
1822         int ret_val = -ENOMSG;
1823         struct inet_sock *sk_inet;
1824         unsigned char *cipso_ptr;
1825         u32 doi;
1826         struct cipso_v4_doi *doi_def;
1827
1828         sk_inet = inet_sk(sk);
1829         if (sk_inet->opt == NULL || sk_inet->opt->cipso == 0)
1830                 return -ENOMSG;
1831         cipso_ptr = sk_inet->opt->__data + sk_inet->opt->cipso -
1832                 sizeof(struct iphdr);
1833         ret_val = cipso_v4_cache_check(cipso_ptr, cipso_ptr[1], secattr);
1834         if (ret_val == 0)
1835                 return ret_val;
1836
1837         doi = ntohl(*(__be32 *)&cipso_ptr[2]);
1838         rcu_read_lock();
1839         doi_def = cipso_v4_doi_search(doi);
1840         if (doi_def == NULL) {
1841                 rcu_read_unlock();
1842                 return -ENOMSG;
1843         }
1844
1845         /* XXX - This code assumes only one tag per CIPSO option which isn't
1846          * really a good assumption to make but since we only support the MAC
1847          * tags right now it is a safe assumption. */
1848         switch (cipso_ptr[6]) {
1849         case CIPSO_V4_TAG_RBITMAP:
1850                 ret_val = cipso_v4_parsetag_rbm(doi_def,
1851                                                 &cipso_ptr[6],
1852                                                 secattr);
1853                 break;
1854         case CIPSO_V4_TAG_ENUM:
1855                 ret_val = cipso_v4_parsetag_enum(doi_def,
1856                                                  &cipso_ptr[6],
1857                                                  secattr);
1858                 break;
1859         case CIPSO_V4_TAG_RANGE:
1860                 ret_val = cipso_v4_parsetag_rng(doi_def,
1861                                                 &cipso_ptr[6],
1862                                                 secattr);
1863                 break;
1864         }
1865         rcu_read_unlock();
1866
1867         return ret_val;
1868 }
1869
1870 /**
1871  * cipso_v4_socket_getattr - Get the security attributes from a socket
1872  * @sock: the socket
1873  * @secattr: the security attributes
1874  *
1875  * Description:
1876  * Query @sock to see if there is a CIPSO option attached to the socket and if
1877  * there is return the CIPSO security attributes in @secattr.  Returns zero on
1878  * success and negative values on failure.
1879  *
1880  */
1881 int cipso_v4_socket_getattr(const struct socket *sock,
1882                             struct netlbl_lsm_secattr *secattr)
1883 {
1884         int ret_val;
1885
1886         lock_sock(sock->sk);
1887         ret_val = cipso_v4_sock_getattr(sock->sk, secattr);
1888         release_sock(sock->sk);
1889
1890         return ret_val;
1891 }
1892
1893 /**
1894  * cipso_v4_skbuff_getattr - Get the security attributes from the CIPSO option
1895  * @skb: the packet
1896  * @secattr: the security attributes
1897  *
1898  * Description:
1899  * Parse the given packet's CIPSO option and return the security attributes.
1900  * Returns zero on success and negative values on failure.
1901  *
1902  */
1903 int cipso_v4_skbuff_getattr(const struct sk_buff *skb,
1904                             struct netlbl_lsm_secattr *secattr)
1905 {
1906         int ret_val = -ENOMSG;
1907         unsigned char *cipso_ptr;
1908         u32 doi;
1909         struct cipso_v4_doi *doi_def;
1910
1911         cipso_ptr = CIPSO_V4_OPTPTR(skb);
1912         if (cipso_v4_cache_check(cipso_ptr, cipso_ptr[1], secattr) == 0)
1913                 return 0;
1914
1915         doi = ntohl(*(__be32 *)&cipso_ptr[2]);
1916         rcu_read_lock();
1917         doi_def = cipso_v4_doi_search(doi);
1918         if (doi_def == NULL)
1919                 goto skbuff_getattr_return;
1920
1921         /* XXX - This code assumes only one tag per CIPSO option which isn't
1922          * really a good assumption to make but since we only support the MAC
1923          * tags right now it is a safe assumption. */
1924         switch (cipso_ptr[6]) {
1925         case CIPSO_V4_TAG_RBITMAP:
1926                 ret_val = cipso_v4_parsetag_rbm(doi_def,
1927                                                 &cipso_ptr[6],
1928                                                 secattr);
1929                 break;
1930         case CIPSO_V4_TAG_ENUM:
1931                 ret_val = cipso_v4_parsetag_enum(doi_def,
1932                                                  &cipso_ptr[6],
1933                                                  secattr);
1934                 break;
1935         }
1936
1937 skbuff_getattr_return:
1938         rcu_read_unlock();
1939         return ret_val;
1940 }
1941
1942 /*
1943  * Setup Functions
1944  */
1945
1946 /**
1947  * cipso_v4_init - Initialize the CIPSO module
1948  *
1949  * Description:
1950  * Initialize the CIPSO module and prepare it for use.  Returns zero on success
1951  * and negative values on failure.
1952  *
1953  */
1954 static int __init cipso_v4_init(void)
1955 {
1956         int ret_val;
1957
1958         ret_val = cipso_v4_cache_init();
1959         if (ret_val != 0)
1960                 panic("Failed to initialize the CIPSO/IPv4 cache (%d)\n",
1961                       ret_val);
1962
1963         return 0;
1964 }
1965
1966 subsys_initcall(cipso_v4_init);