[NETLABEL]: Use kmemdup in cipso_ipv4.c
[linux-drm-fsl-dcu.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                         if (prev_entry == NULL) {
323                                 spin_unlock_bh(&cipso_v4_cache[bkt].lock);
324                                 return 0;
325                         }
326
327                         if (prev_entry->activity > 0)
328                                 prev_entry->activity -= 1;
329                         if (entry->activity > prev_entry->activity &&
330                             entry->activity - prev_entry->activity >
331                             CIPSO_V4_CACHE_REORDERLIMIT) {
332                                 __list_del(entry->list.prev, entry->list.next);
333                                 __list_add(&entry->list,
334                                            prev_entry->list.prev,
335                                            &prev_entry->list);
336                         }
337
338                         spin_unlock_bh(&cipso_v4_cache[bkt].lock);
339                         return 0;
340                 }
341                 prev_entry = entry;
342         }
343         spin_unlock_bh(&cipso_v4_cache[bkt].lock);
344
345         return -ENOENT;
346 }
347
348 /**
349  * cipso_v4_cache_add - Add an entry to the CIPSO cache
350  * @skb: the packet
351  * @secattr: the packet's security attributes
352  *
353  * Description:
354  * Add a new entry into the CIPSO label mapping cache.  Add the new entry to
355  * head of the cache bucket's list, if the cache bucket is out of room remove
356  * the last entry in the list first.  It is important to note that there is
357  * currently no checking for duplicate keys.  Returns zero on success,
358  * negative values on failure.
359  *
360  */
361 int cipso_v4_cache_add(const struct sk_buff *skb,
362                        const struct netlbl_lsm_secattr *secattr)
363 {
364         int ret_val = -EPERM;
365         u32 bkt;
366         struct cipso_v4_map_cache_entry *entry = NULL;
367         struct cipso_v4_map_cache_entry *old_entry = NULL;
368         unsigned char *cipso_ptr;
369         u32 cipso_ptr_len;
370
371         if (!cipso_v4_cache_enabled || cipso_v4_cache_bucketsize <= 0)
372                 return 0;
373
374         cipso_ptr = CIPSO_V4_OPTPTR(skb);
375         cipso_ptr_len = cipso_ptr[1];
376
377         entry = kzalloc(sizeof(*entry), GFP_ATOMIC);
378         if (entry == NULL)
379                 return -ENOMEM;
380         entry->key = kmemdup(cipso_ptr, cipso_ptr_len, GFP_ATOMIC);
381         if (entry->key == NULL) {
382                 ret_val = -ENOMEM;
383                 goto cache_add_failure;
384         }
385         entry->key_len = cipso_ptr_len;
386         entry->hash = cipso_v4_map_cache_hash(cipso_ptr, cipso_ptr_len);
387         atomic_inc(&secattr->cache->refcount);
388         entry->lsm_data = secattr->cache;
389
390         bkt = entry->hash & (CIPSO_V4_CACHE_BUCKETBITS - 1);
391         spin_lock_bh(&cipso_v4_cache[bkt].lock);
392         if (cipso_v4_cache[bkt].size < cipso_v4_cache_bucketsize) {
393                 list_add(&entry->list, &cipso_v4_cache[bkt].list);
394                 cipso_v4_cache[bkt].size += 1;
395         } else {
396                 old_entry = list_entry(cipso_v4_cache[bkt].list.prev,
397                                        struct cipso_v4_map_cache_entry, list);
398                 list_del(&old_entry->list);
399                 list_add(&entry->list, &cipso_v4_cache[bkt].list);
400                 cipso_v4_cache_entry_free(old_entry);
401         }
402         spin_unlock_bh(&cipso_v4_cache[bkt].lock);
403
404         return 0;
405
406 cache_add_failure:
407         if (entry)
408                 cipso_v4_cache_entry_free(entry);
409         return ret_val;
410 }
411
412 /*
413  * DOI List Functions
414  */
415
416 /**
417  * cipso_v4_doi_search - Searches for a DOI definition
418  * @doi: the DOI to search for
419  *
420  * Description:
421  * Search the DOI definition list for a DOI definition with a DOI value that
422  * matches @doi.  The caller is responsibile for calling rcu_read_[un]lock().
423  * Returns a pointer to the DOI definition on success and NULL on failure.
424  */
425 static struct cipso_v4_doi *cipso_v4_doi_search(u32 doi)
426 {
427         struct cipso_v4_doi *iter;
428
429         list_for_each_entry_rcu(iter, &cipso_v4_doi_list, list)
430                 if (iter->doi == doi && iter->valid)
431                         return iter;
432         return NULL;
433 }
434
435 /**
436  * cipso_v4_doi_add - Add a new DOI to the CIPSO protocol engine
437  * @doi_def: the DOI structure
438  *
439  * Description:
440  * The caller defines a new DOI for use by the CIPSO engine and calls this
441  * function to add it to the list of acceptable domains.  The caller must
442  * ensure that the mapping table specified in @doi_def->map meets all of the
443  * requirements of the mapping type (see cipso_ipv4.h for details).  Returns
444  * zero on success and non-zero on failure.
445  *
446  */
447 int cipso_v4_doi_add(struct cipso_v4_doi *doi_def)
448 {
449         if (doi_def == NULL || doi_def->doi == CIPSO_V4_DOI_UNKNOWN)
450                 return -EINVAL;
451
452         doi_def->valid = 1;
453         INIT_RCU_HEAD(&doi_def->rcu);
454         INIT_LIST_HEAD(&doi_def->dom_list);
455
456         rcu_read_lock();
457         if (cipso_v4_doi_search(doi_def->doi) != NULL)
458                 goto doi_add_failure_rlock;
459         spin_lock(&cipso_v4_doi_list_lock);
460         if (cipso_v4_doi_search(doi_def->doi) != NULL)
461                 goto doi_add_failure_slock;
462         list_add_tail_rcu(&doi_def->list, &cipso_v4_doi_list);
463         spin_unlock(&cipso_v4_doi_list_lock);
464         rcu_read_unlock();
465
466         return 0;
467
468 doi_add_failure_slock:
469         spin_unlock(&cipso_v4_doi_list_lock);
470 doi_add_failure_rlock:
471         rcu_read_unlock();
472         return -EEXIST;
473 }
474
475 /**
476  * cipso_v4_doi_remove - Remove an existing DOI from the CIPSO protocol engine
477  * @doi: the DOI value
478  * @audit_secid: the LSM secid to use in the audit message
479  * @callback: the DOI cleanup/free callback
480  *
481  * Description:
482  * Removes a DOI definition from the CIPSO engine, @callback is called to
483  * free any memory.  The NetLabel routines will be called to release their own
484  * LSM domain mappings as well as our own domain list.  Returns zero on
485  * success and negative values on failure.
486  *
487  */
488 int cipso_v4_doi_remove(u32 doi,
489                         struct netlbl_audit *audit_info,
490                         void (*callback) (struct rcu_head * head))
491 {
492         struct cipso_v4_doi *doi_def;
493         struct cipso_v4_domhsh_entry *dom_iter;
494
495         rcu_read_lock();
496         if (cipso_v4_doi_search(doi) != NULL) {
497                 spin_lock(&cipso_v4_doi_list_lock);
498                 doi_def = cipso_v4_doi_search(doi);
499                 if (doi_def == NULL) {
500                         spin_unlock(&cipso_v4_doi_list_lock);
501                         rcu_read_unlock();
502                         return -ENOENT;
503                 }
504                 doi_def->valid = 0;
505                 list_del_rcu(&doi_def->list);
506                 spin_unlock(&cipso_v4_doi_list_lock);
507                 list_for_each_entry_rcu(dom_iter, &doi_def->dom_list, list)
508                         if (dom_iter->valid)
509                                 netlbl_domhsh_remove(dom_iter->domain,
510                                                      audit_info);
511                 cipso_v4_cache_invalidate();
512                 rcu_read_unlock();
513
514                 call_rcu(&doi_def->rcu, callback);
515                 return 0;
516         }
517         rcu_read_unlock();
518
519         return -ENOENT;
520 }
521
522 /**
523  * cipso_v4_doi_getdef - Returns a pointer to a valid DOI definition
524  * @doi: the DOI value
525  *
526  * Description:
527  * Searches for a valid DOI definition and if one is found it is returned to
528  * the caller.  Otherwise NULL is returned.  The caller must ensure that
529  * rcu_read_lock() is held while accessing the returned definition.
530  *
531  */
532 struct cipso_v4_doi *cipso_v4_doi_getdef(u32 doi)
533 {
534         return cipso_v4_doi_search(doi);
535 }
536
537 /**
538  * cipso_v4_doi_walk - Iterate through the DOI definitions
539  * @skip_cnt: skip past this number of DOI definitions, updated
540  * @callback: callback for each DOI definition
541  * @cb_arg: argument for the callback function
542  *
543  * Description:
544  * Iterate over the DOI definition list, skipping the first @skip_cnt entries.
545  * For each entry call @callback, if @callback returns a negative value stop
546  * 'walking' through the list and return.  Updates the value in @skip_cnt upon
547  * return.  Returns zero on success, negative values on failure.
548  *
549  */
550 int cipso_v4_doi_walk(u32 *skip_cnt,
551                      int (*callback) (struct cipso_v4_doi *doi_def, void *arg),
552                      void *cb_arg)
553 {
554         int ret_val = -ENOENT;
555         u32 doi_cnt = 0;
556         struct cipso_v4_doi *iter_doi;
557
558         rcu_read_lock();
559         list_for_each_entry_rcu(iter_doi, &cipso_v4_doi_list, list)
560                 if (iter_doi->valid) {
561                         if (doi_cnt++ < *skip_cnt)
562                                 continue;
563                         ret_val = callback(iter_doi, cb_arg);
564                         if (ret_val < 0) {
565                                 doi_cnt--;
566                                 goto doi_walk_return;
567                         }
568                 }
569
570 doi_walk_return:
571         rcu_read_unlock();
572         *skip_cnt = doi_cnt;
573         return ret_val;
574 }
575
576 /**
577  * cipso_v4_doi_domhsh_add - Adds a domain entry to a DOI definition
578  * @doi_def: the DOI definition
579  * @domain: the domain to add
580  *
581  * Description:
582  * Adds the @domain to the the DOI specified by @doi_def, this function
583  * should only be called by external functions (i.e. NetLabel).  This function
584  * does allocate memory.  Returns zero on success, negative values on failure.
585  *
586  */
587 int cipso_v4_doi_domhsh_add(struct cipso_v4_doi *doi_def, const char *domain)
588 {
589         struct cipso_v4_domhsh_entry *iter;
590         struct cipso_v4_domhsh_entry *new_dom;
591
592         new_dom = kzalloc(sizeof(*new_dom), GFP_KERNEL);
593         if (new_dom == NULL)
594                 return -ENOMEM;
595         if (domain) {
596                 new_dom->domain = kstrdup(domain, GFP_KERNEL);
597                 if (new_dom->domain == NULL) {
598                         kfree(new_dom);
599                         return -ENOMEM;
600                 }
601         }
602         new_dom->valid = 1;
603         INIT_RCU_HEAD(&new_dom->rcu);
604
605         rcu_read_lock();
606         spin_lock(&cipso_v4_doi_list_lock);
607         list_for_each_entry_rcu(iter, &doi_def->dom_list, list)
608                 if (iter->valid &&
609                     ((domain != NULL && iter->domain != NULL &&
610                       strcmp(iter->domain, domain) == 0) ||
611                      (domain == NULL && iter->domain == NULL))) {
612                         spin_unlock(&cipso_v4_doi_list_lock);
613                         rcu_read_unlock();
614                         kfree(new_dom->domain);
615                         kfree(new_dom);
616                         return -EEXIST;
617                 }
618         list_add_tail_rcu(&new_dom->list, &doi_def->dom_list);
619         spin_unlock(&cipso_v4_doi_list_lock);
620         rcu_read_unlock();
621
622         return 0;
623 }
624
625 /**
626  * cipso_v4_doi_domhsh_remove - Removes a domain entry from a DOI definition
627  * @doi_def: the DOI definition
628  * @domain: the domain to remove
629  *
630  * Description:
631  * Removes the @domain from the DOI specified by @doi_def, this function
632  * should only be called by external functions (i.e. NetLabel).   Returns zero
633  * on success and negative values on error.
634  *
635  */
636 int cipso_v4_doi_domhsh_remove(struct cipso_v4_doi *doi_def,
637                                const char *domain)
638 {
639         struct cipso_v4_domhsh_entry *iter;
640
641         rcu_read_lock();
642         spin_lock(&cipso_v4_doi_list_lock);
643         list_for_each_entry_rcu(iter, &doi_def->dom_list, list)
644                 if (iter->valid &&
645                     ((domain != NULL && iter->domain != NULL &&
646                       strcmp(iter->domain, domain) == 0) ||
647                      (domain == NULL && iter->domain == NULL))) {
648                         iter->valid = 0;
649                         list_del_rcu(&iter->list);
650                         spin_unlock(&cipso_v4_doi_list_lock);
651                         rcu_read_unlock();
652                         call_rcu(&iter->rcu, cipso_v4_doi_domhsh_free);
653
654                         return 0;
655                 }
656         spin_unlock(&cipso_v4_doi_list_lock);
657         rcu_read_unlock();
658
659         return -ENOENT;
660 }
661
662 /*
663  * Label Mapping Functions
664  */
665
666 /**
667  * cipso_v4_map_lvl_valid - Checks to see if the given level is understood
668  * @doi_def: the DOI definition
669  * @level: the level to check
670  *
671  * Description:
672  * Checks the given level against the given DOI definition and returns a
673  * negative value if the level does not have a valid mapping and a zero value
674  * if the level is defined by the DOI.
675  *
676  */
677 static int cipso_v4_map_lvl_valid(const struct cipso_v4_doi *doi_def, u8 level)
678 {
679         switch (doi_def->type) {
680         case CIPSO_V4_MAP_PASS:
681                 return 0;
682         case CIPSO_V4_MAP_STD:
683                 if (doi_def->map.std->lvl.cipso[level] < CIPSO_V4_INV_LVL)
684                         return 0;
685                 break;
686         }
687
688         return -EFAULT;
689 }
690
691 /**
692  * cipso_v4_map_lvl_hton - Perform a level mapping from the host to the network
693  * @doi_def: the DOI definition
694  * @host_lvl: the host MLS level
695  * @net_lvl: the network/CIPSO MLS level
696  *
697  * Description:
698  * Perform a label mapping to translate a local MLS level to the correct
699  * CIPSO level using the given DOI definition.  Returns zero on success,
700  * negative values otherwise.
701  *
702  */
703 static int cipso_v4_map_lvl_hton(const struct cipso_v4_doi *doi_def,
704                                  u32 host_lvl,
705                                  u32 *net_lvl)
706 {
707         switch (doi_def->type) {
708         case CIPSO_V4_MAP_PASS:
709                 *net_lvl = host_lvl;
710                 return 0;
711         case CIPSO_V4_MAP_STD:
712                 if (host_lvl < doi_def->map.std->lvl.local_size) {
713                         *net_lvl = doi_def->map.std->lvl.local[host_lvl];
714                         return 0;
715                 }
716                 break;
717         }
718
719         return -EINVAL;
720 }
721
722 /**
723  * cipso_v4_map_lvl_ntoh - Perform a level mapping from the network to the host
724  * @doi_def: the DOI definition
725  * @net_lvl: the network/CIPSO MLS level
726  * @host_lvl: the host MLS level
727  *
728  * Description:
729  * Perform a label mapping to translate a CIPSO level to the correct local MLS
730  * level using the given DOI definition.  Returns zero on success, negative
731  * values otherwise.
732  *
733  */
734 static int cipso_v4_map_lvl_ntoh(const struct cipso_v4_doi *doi_def,
735                                  u32 net_lvl,
736                                  u32 *host_lvl)
737 {
738         struct cipso_v4_std_map_tbl *map_tbl;
739
740         switch (doi_def->type) {
741         case CIPSO_V4_MAP_PASS:
742                 *host_lvl = net_lvl;
743                 return 0;
744         case CIPSO_V4_MAP_STD:
745                 map_tbl = doi_def->map.std;
746                 if (net_lvl < map_tbl->lvl.cipso_size &&
747                     map_tbl->lvl.cipso[net_lvl] < CIPSO_V4_INV_LVL) {
748                         *host_lvl = doi_def->map.std->lvl.cipso[net_lvl];
749                         return 0;
750                 }
751                 break;
752         }
753
754         return -EINVAL;
755 }
756
757 /**
758  * cipso_v4_map_cat_rbm_valid - Checks to see if the category bitmap is valid
759  * @doi_def: the DOI definition
760  * @bitmap: category bitmap
761  * @bitmap_len: bitmap length in bytes
762  *
763  * Description:
764  * Checks the given category bitmap against the given DOI definition and
765  * returns a negative value if any of the categories in the bitmap do not have
766  * a valid mapping and a zero value if all of the categories are valid.
767  *
768  */
769 static int cipso_v4_map_cat_rbm_valid(const struct cipso_v4_doi *doi_def,
770                                       const unsigned char *bitmap,
771                                       u32 bitmap_len)
772 {
773         int cat = -1;
774         u32 bitmap_len_bits = bitmap_len * 8;
775         u32 cipso_cat_size;
776         u32 *cipso_array;
777
778         switch (doi_def->type) {
779         case CIPSO_V4_MAP_PASS:
780                 return 0;
781         case CIPSO_V4_MAP_STD:
782                 cipso_cat_size = doi_def->map.std->cat.cipso_size;
783                 cipso_array = doi_def->map.std->cat.cipso;
784                 for (;;) {
785                         cat = cipso_v4_bitmap_walk(bitmap,
786                                                    bitmap_len_bits,
787                                                    cat + 1,
788                                                    1);
789                         if (cat < 0)
790                                 break;
791                         if (cat >= cipso_cat_size ||
792                             cipso_array[cat] >= CIPSO_V4_INV_CAT)
793                                 return -EFAULT;
794                 }
795
796                 if (cat == -1)
797                         return 0;
798                 break;
799         }
800
801         return -EFAULT;
802 }
803
804 /**
805  * cipso_v4_map_cat_rbm_hton - Perform a category mapping from host to network
806  * @doi_def: the DOI definition
807  * @host_cat: the category bitmap in host format
808  * @host_cat_len: the length of the host's category bitmap in bytes
809  * @net_cat: the zero'd out category bitmap in network/CIPSO format
810  * @net_cat_len: the length of the CIPSO bitmap in bytes
811  *
812  * Description:
813  * Perform a label mapping to translate a local MLS category bitmap to the
814  * correct CIPSO bitmap using the given DOI definition.  Returns the minimum
815  * size in bytes of the network bitmap on success, negative values otherwise.
816  *
817  */
818 static int cipso_v4_map_cat_rbm_hton(const struct cipso_v4_doi *doi_def,
819                                      const unsigned char *host_cat,
820                                      u32 host_cat_len,
821                                      unsigned char *net_cat,
822                                      u32 net_cat_len)
823 {
824         int host_spot = -1;
825         u32 net_spot;
826         u32 net_spot_max = 0;
827         u32 host_clen_bits = host_cat_len * 8;
828         u32 net_clen_bits = net_cat_len * 8;
829         u32 host_cat_size;
830         u32 *host_cat_array;
831
832         switch (doi_def->type) {
833         case CIPSO_V4_MAP_PASS:
834                 net_spot_max = host_cat_len;
835                 while (net_spot_max > 0 && host_cat[net_spot_max - 1] == 0)
836                         net_spot_max--;
837                 if (net_spot_max > net_cat_len)
838                         return -EINVAL;
839                 memcpy(net_cat, host_cat, net_spot_max);
840                 return net_spot_max;
841         case CIPSO_V4_MAP_STD:
842                 host_cat_size = doi_def->map.std->cat.local_size;
843                 host_cat_array = doi_def->map.std->cat.local;
844                 for (;;) {
845                         host_spot = cipso_v4_bitmap_walk(host_cat,
846                                                          host_clen_bits,
847                                                          host_spot + 1,
848                                                          1);
849                         if (host_spot < 0)
850                                 break;
851                         if (host_spot >= host_cat_size)
852                                 return -EPERM;
853
854                         net_spot = host_cat_array[host_spot];
855                         if (net_spot >= net_clen_bits)
856                                 return -ENOSPC;
857                         cipso_v4_bitmap_setbit(net_cat, net_spot, 1);
858
859                         if (net_spot > net_spot_max)
860                                 net_spot_max = net_spot;
861                 }
862
863                 if (host_spot == -2)
864                         return -EFAULT;
865
866                 if (++net_spot_max % 8)
867                         return net_spot_max / 8 + 1;
868                 return net_spot_max / 8;
869         }
870
871         return -EINVAL;
872 }
873
874 /**
875  * cipso_v4_map_cat_rbm_ntoh - Perform a category mapping from network to host
876  * @doi_def: the DOI definition
877  * @net_cat: the category bitmap in network/CIPSO format
878  * @net_cat_len: the length of the CIPSO bitmap in bytes
879  * @host_cat: the zero'd out category bitmap in host format
880  * @host_cat_len: the length of the host's category bitmap in bytes
881  *
882  * Description:
883  * Perform a label mapping to translate a CIPSO bitmap to the correct local
884  * MLS category bitmap using the given DOI definition.  Returns the minimum
885  * size in bytes of the host bitmap on success, negative values otherwise.
886  *
887  */
888 static int cipso_v4_map_cat_rbm_ntoh(const struct cipso_v4_doi *doi_def,
889                                      const unsigned char *net_cat,
890                                      u32 net_cat_len,
891                                      unsigned char *host_cat,
892                                      u32 host_cat_len)
893 {
894         u32 host_spot;
895         u32 host_spot_max = 0;
896         int net_spot = -1;
897         u32 net_clen_bits = net_cat_len * 8;
898         u32 host_clen_bits = host_cat_len * 8;
899         u32 net_cat_size;
900         u32 *net_cat_array;
901
902         switch (doi_def->type) {
903         case CIPSO_V4_MAP_PASS:
904                 if (net_cat_len > host_cat_len)
905                         return -EINVAL;
906                 memcpy(host_cat, net_cat, net_cat_len);
907                 return net_cat_len;
908         case CIPSO_V4_MAP_STD:
909                 net_cat_size = doi_def->map.std->cat.cipso_size;
910                 net_cat_array = doi_def->map.std->cat.cipso;
911                 for (;;) {
912                         net_spot = cipso_v4_bitmap_walk(net_cat,
913                                                         net_clen_bits,
914                                                         net_spot + 1,
915                                                         1);
916                         if (net_spot < 0)
917                                 break;
918                         if (net_spot >= net_cat_size ||
919                             net_cat_array[net_spot] >= CIPSO_V4_INV_CAT)
920                                 return -EPERM;
921
922                         host_spot = net_cat_array[net_spot];
923                         if (host_spot >= host_clen_bits)
924                                 return -ENOSPC;
925                         cipso_v4_bitmap_setbit(host_cat, host_spot, 1);
926
927                         if (host_spot > host_spot_max)
928                                 host_spot_max = host_spot;
929                 }
930
931                 if (net_spot == -2)
932                         return -EFAULT;
933
934                 if (++host_spot_max % 8)
935                         return host_spot_max / 8 + 1;
936                 return host_spot_max / 8;
937         }
938
939         return -EINVAL;
940 }
941
942 /*
943  * Protocol Handling Functions
944  */
945
946 #define CIPSO_V4_HDR_LEN              6
947
948 /**
949  * cipso_v4_gentag_hdr - Generate a CIPSO option header
950  * @doi_def: the DOI definition
951  * @len: the total tag length in bytes
952  * @buf: the CIPSO option buffer
953  *
954  * Description:
955  * Write a CIPSO header into the beginning of @buffer.  Return zero on success,
956  * negative values on failure.
957  *
958  */
959 static int cipso_v4_gentag_hdr(const struct cipso_v4_doi *doi_def,
960                                u32 len,
961                                unsigned char *buf)
962 {
963         if (CIPSO_V4_HDR_LEN + len > 40)
964                 return -ENOSPC;
965
966         buf[0] = IPOPT_CIPSO;
967         buf[1] = CIPSO_V4_HDR_LEN + len;
968         *(__be32 *)&buf[2] = htonl(doi_def->doi);
969
970         return 0;
971 }
972
973 #define CIPSO_V4_TAG1_CAT_LEN         30
974
975 /**
976  * cipso_v4_gentag_rbm - Generate a CIPSO restricted bitmap tag (type #1)
977  * @doi_def: the DOI definition
978  * @secattr: the security attributes
979  * @buffer: the option buffer
980  * @buffer_len: length of buffer in bytes
981  *
982  * Description:
983  * Generate a CIPSO option using the restricted bitmap tag, tag type #1.  The
984  * actual buffer length may be larger than the indicated size due to
985  * translation between host and network category bitmaps.  Returns zero on
986  * success, negative values on failure.
987  *
988  */
989 static int cipso_v4_gentag_rbm(const struct cipso_v4_doi *doi_def,
990                                const struct netlbl_lsm_secattr *secattr,
991                                unsigned char **buffer,
992                                u32 *buffer_len)
993 {
994         int ret_val = -EPERM;
995         unsigned char *buf = NULL;
996         u32 buf_len;
997         u32 level;
998
999         if (secattr->mls_cat) {
1000                 buf = kzalloc(CIPSO_V4_HDR_LEN + 4 + CIPSO_V4_TAG1_CAT_LEN,
1001                               GFP_ATOMIC);
1002                 if (buf == NULL)
1003                         return -ENOMEM;
1004
1005                 ret_val = cipso_v4_map_cat_rbm_hton(doi_def,
1006                                                     secattr->mls_cat,
1007                                                     secattr->mls_cat_len,
1008                                                     &buf[CIPSO_V4_HDR_LEN + 4],
1009                                                     CIPSO_V4_TAG1_CAT_LEN);
1010                 if (ret_val < 0)
1011                         goto gentag_failure;
1012
1013                 /* This will send packets using the "optimized" format when
1014                  * possibile as specified in  section 3.4.2.6 of the
1015                  * CIPSO draft. */
1016                 if (cipso_v4_rbm_optfmt && (ret_val > 0 && ret_val < 10))
1017                         ret_val = 10;
1018
1019                 buf_len = 4 + ret_val;
1020         } else {
1021                 buf = kzalloc(CIPSO_V4_HDR_LEN + 4, GFP_ATOMIC);
1022                 if (buf == NULL)
1023                         return -ENOMEM;
1024                 buf_len = 4;
1025         }
1026
1027         ret_val = cipso_v4_map_lvl_hton(doi_def, secattr->mls_lvl, &level);
1028         if (ret_val != 0)
1029                 goto gentag_failure;
1030
1031         ret_val = cipso_v4_gentag_hdr(doi_def, buf_len, buf);
1032         if (ret_val != 0)
1033                 goto gentag_failure;
1034
1035         buf[CIPSO_V4_HDR_LEN] = 0x01;
1036         buf[CIPSO_V4_HDR_LEN + 1] = buf_len;
1037         buf[CIPSO_V4_HDR_LEN + 3] = level;
1038
1039         *buffer = buf;
1040         *buffer_len = CIPSO_V4_HDR_LEN + buf_len;
1041
1042         return 0;
1043
1044 gentag_failure:
1045         kfree(buf);
1046         return ret_val;
1047 }
1048
1049 /**
1050  * cipso_v4_parsetag_rbm - Parse a CIPSO restricted bitmap tag
1051  * @doi_def: the DOI definition
1052  * @tag: the CIPSO tag
1053  * @secattr: the security attributes
1054  *
1055  * Description:
1056  * Parse a CIPSO restricted bitmap tag (tag type #1) and return the security
1057  * attributes in @secattr.  Return zero on success, negatives values on
1058  * failure.
1059  *
1060  */
1061 static int cipso_v4_parsetag_rbm(const struct cipso_v4_doi *doi_def,
1062                                  const unsigned char *tag,
1063                                  struct netlbl_lsm_secattr *secattr)
1064 {
1065         int ret_val;
1066         u8 tag_len = tag[1];
1067         u32 level;
1068
1069         ret_val = cipso_v4_map_lvl_ntoh(doi_def, tag[3], &level);
1070         if (ret_val != 0)
1071                 return ret_val;
1072         secattr->mls_lvl = level;
1073         secattr->mls_lvl_vld = 1;
1074
1075         if (tag_len > 4) {
1076                 switch (doi_def->type) {
1077                 case CIPSO_V4_MAP_PASS:
1078                         secattr->mls_cat_len = tag_len - 4;
1079                         break;
1080                 case CIPSO_V4_MAP_STD:
1081                         secattr->mls_cat_len =
1082                                 doi_def->map.std->cat.local_size;
1083                         break;
1084                 }
1085                 secattr->mls_cat = kzalloc(secattr->mls_cat_len, GFP_ATOMIC);
1086                 if (secattr->mls_cat == NULL)
1087                         return -ENOMEM;
1088
1089                 ret_val = cipso_v4_map_cat_rbm_ntoh(doi_def,
1090                                                     &tag[4],
1091                                                     tag_len - 4,
1092                                                     secattr->mls_cat,
1093                                                     secattr->mls_cat_len);
1094                 if (ret_val < 0) {
1095                         kfree(secattr->mls_cat);
1096                         return ret_val;
1097                 }
1098                 secattr->mls_cat_len = ret_val;
1099         }
1100
1101         return 0;
1102 }
1103
1104 /**
1105  * cipso_v4_validate - Validate a CIPSO option
1106  * @option: the start of the option, on error it is set to point to the error
1107  *
1108  * Description:
1109  * This routine is called to validate a CIPSO option, it checks all of the
1110  * fields to ensure that they are at least valid, see the draft snippet below
1111  * for details.  If the option is valid then a zero value is returned and
1112  * the value of @option is unchanged.  If the option is invalid then a
1113  * non-zero value is returned and @option is adjusted to point to the
1114  * offending portion of the option.  From the IETF draft ...
1115  *
1116  *  "If any field within the CIPSO options, such as the DOI identifier, is not
1117  *   recognized the IP datagram is discarded and an ICMP 'parameter problem'
1118  *   (type 12) is generated and returned.  The ICMP code field is set to 'bad
1119  *   parameter' (code 0) and the pointer is set to the start of the CIPSO field
1120  *   that is unrecognized."
1121  *
1122  */
1123 int cipso_v4_validate(unsigned char **option)
1124 {
1125         unsigned char *opt = *option;
1126         unsigned char *tag;
1127         unsigned char opt_iter;
1128         unsigned char err_offset = 0;
1129         u8 opt_len;
1130         u8 tag_len;
1131         struct cipso_v4_doi *doi_def = NULL;
1132         u32 tag_iter;
1133
1134         /* caller already checks for length values that are too large */
1135         opt_len = opt[1];
1136         if (opt_len < 8) {
1137                 err_offset = 1;
1138                 goto validate_return;
1139         }
1140
1141         rcu_read_lock();
1142         doi_def = cipso_v4_doi_getdef(ntohl(*((__be32 *)&opt[2])));
1143         if (doi_def == NULL) {
1144                 err_offset = 2;
1145                 goto validate_return_locked;
1146         }
1147
1148         opt_iter = 6;
1149         tag = opt + opt_iter;
1150         while (opt_iter < opt_len) {
1151                 for (tag_iter = 0; doi_def->tags[tag_iter] != tag[0];)
1152                         if (doi_def->tags[tag_iter] == CIPSO_V4_TAG_INVALID ||
1153                             ++tag_iter == CIPSO_V4_TAG_MAXCNT) {
1154                                 err_offset = opt_iter;
1155                                 goto validate_return_locked;
1156                         }
1157
1158                 tag_len = tag[1];
1159                 if (tag_len > (opt_len - opt_iter)) {
1160                         err_offset = opt_iter + 1;
1161                         goto validate_return_locked;
1162                 }
1163
1164                 switch (tag[0]) {
1165                 case CIPSO_V4_TAG_RBITMAP:
1166                         if (tag_len < 4) {
1167                                 err_offset = opt_iter + 1;
1168                                 goto validate_return_locked;
1169                         }
1170
1171                         /* We are already going to do all the verification
1172                          * necessary at the socket layer so from our point of
1173                          * view it is safe to turn these checks off (and less
1174                          * work), however, the CIPSO draft says we should do
1175                          * all the CIPSO validations here but it doesn't
1176                          * really specify _exactly_ what we need to validate
1177                          * ... so, just make it a sysctl tunable. */
1178                         if (cipso_v4_rbm_strictvalid) {
1179                                 if (cipso_v4_map_lvl_valid(doi_def,
1180                                                            tag[3]) < 0) {
1181                                         err_offset = opt_iter + 3;
1182                                         goto validate_return_locked;
1183                                 }
1184                                 if (tag_len > 4 &&
1185                                     cipso_v4_map_cat_rbm_valid(doi_def,
1186                                                             &tag[4],
1187                                                             tag_len - 4) < 0) {
1188                                         err_offset = opt_iter + 4;
1189                                         goto validate_return_locked;
1190                                 }
1191                         }
1192                         break;
1193                 default:
1194                         err_offset = opt_iter;
1195                         goto validate_return_locked;
1196                 }
1197
1198                 tag += tag_len;
1199                 opt_iter += tag_len;
1200         }
1201
1202 validate_return_locked:
1203         rcu_read_unlock();
1204 validate_return:
1205         *option = opt + err_offset;
1206         return err_offset;
1207 }
1208
1209 /**
1210  * cipso_v4_error - Send the correct reponse for a bad packet
1211  * @skb: the packet
1212  * @error: the error code
1213  * @gateway: CIPSO gateway flag
1214  *
1215  * Description:
1216  * Based on the error code given in @error, send an ICMP error message back to
1217  * the originating host.  From the IETF draft ...
1218  *
1219  *  "If the contents of the CIPSO [option] are valid but the security label is
1220  *   outside of the configured host or port label range, the datagram is
1221  *   discarded and an ICMP 'destination unreachable' (type 3) is generated and
1222  *   returned.  The code field of the ICMP is set to 'communication with
1223  *   destination network administratively prohibited' (code 9) or to
1224  *   'communication with destination host administratively prohibited'
1225  *   (code 10).  The value of the code is dependent on whether the originator
1226  *   of the ICMP message is acting as a CIPSO host or a CIPSO gateway.  The
1227  *   recipient of the ICMP message MUST be able to handle either value.  The
1228  *   same procedure is performed if a CIPSO [option] can not be added to an
1229  *   IP packet because it is too large to fit in the IP options area."
1230  *
1231  *  "If the error is triggered by receipt of an ICMP message, the message is
1232  *   discarded and no response is permitted (consistent with general ICMP
1233  *   processing rules)."
1234  *
1235  */
1236 void cipso_v4_error(struct sk_buff *skb, int error, u32 gateway)
1237 {
1238         if (skb->nh.iph->protocol == IPPROTO_ICMP || error != -EACCES)
1239                 return;
1240
1241         if (gateway)
1242                 icmp_send(skb, ICMP_DEST_UNREACH, ICMP_NET_ANO, 0);
1243         else
1244                 icmp_send(skb, ICMP_DEST_UNREACH, ICMP_HOST_ANO, 0);
1245 }
1246
1247 /**
1248  * cipso_v4_socket_setattr - Add a CIPSO option to a socket
1249  * @sock: the socket
1250  * @doi_def: the CIPSO DOI to use
1251  * @secattr: the specific security attributes of the socket
1252  *
1253  * Description:
1254  * Set the CIPSO option on the given socket using the DOI definition and
1255  * security attributes passed to the function.  This function requires
1256  * exclusive access to @sock->sk, which means it either needs to be in the
1257  * process of being created or locked via lock_sock(sock->sk).  Returns zero on
1258  * success and negative values on failure.
1259  *
1260  */
1261 int cipso_v4_socket_setattr(const struct socket *sock,
1262                             const struct cipso_v4_doi *doi_def,
1263                             const struct netlbl_lsm_secattr *secattr)
1264 {
1265         int ret_val = -EPERM;
1266         u32 iter;
1267         unsigned char *buf = NULL;
1268         u32 buf_len = 0;
1269         u32 opt_len;
1270         struct ip_options *opt = NULL;
1271         struct sock *sk;
1272         struct inet_sock *sk_inet;
1273         struct inet_connection_sock *sk_conn;
1274
1275         /* In the case of sock_create_lite(), the sock->sk field is not
1276          * defined yet but it is not a problem as the only users of these
1277          * "lite" PF_INET sockets are functions which do an accept() call
1278          * afterwards so we will label the socket as part of the accept(). */
1279         sk = sock->sk;
1280         if (sk == NULL)
1281                 return 0;
1282
1283         /* XXX - This code assumes only one tag per CIPSO option which isn't
1284          * really a good assumption to make but since we only support the MAC
1285          * tags right now it is a safe assumption. */
1286         iter = 0;
1287         do {
1288                 switch (doi_def->tags[iter]) {
1289                 case CIPSO_V4_TAG_RBITMAP:
1290                         ret_val = cipso_v4_gentag_rbm(doi_def,
1291                                                       secattr,
1292                                                       &buf,
1293                                                       &buf_len);
1294                         break;
1295                 default:
1296                         ret_val = -EPERM;
1297                         goto socket_setattr_failure;
1298                 }
1299
1300                 iter++;
1301         } while (ret_val != 0 &&
1302                  iter < CIPSO_V4_TAG_MAXCNT &&
1303                  doi_def->tags[iter] != CIPSO_V4_TAG_INVALID);
1304         if (ret_val != 0)
1305                 goto socket_setattr_failure;
1306
1307         /* We can't use ip_options_get() directly because it makes a call to
1308          * ip_options_get_alloc() which allocates memory with GFP_KERNEL and
1309          * we won't always have CAP_NET_RAW even though we _always_ want to
1310          * set the IPOPT_CIPSO option. */
1311         opt_len = (buf_len + 3) & ~3;
1312         opt = kzalloc(sizeof(*opt) + opt_len, GFP_ATOMIC);
1313         if (opt == NULL) {
1314                 ret_val = -ENOMEM;
1315                 goto socket_setattr_failure;
1316         }
1317         memcpy(opt->__data, buf, buf_len);
1318         opt->optlen = opt_len;
1319         opt->is_data = 1;
1320         opt->cipso = sizeof(struct iphdr);
1321         kfree(buf);
1322         buf = NULL;
1323
1324         sk_inet = inet_sk(sk);
1325         if (sk_inet->is_icsk) {
1326                 sk_conn = inet_csk(sk);
1327                 if (sk_inet->opt)
1328                         sk_conn->icsk_ext_hdr_len -= sk_inet->opt->optlen;
1329                 sk_conn->icsk_ext_hdr_len += opt->optlen;
1330                 sk_conn->icsk_sync_mss(sk, sk_conn->icsk_pmtu_cookie);
1331         }
1332         opt = xchg(&sk_inet->opt, opt);
1333         kfree(opt);
1334
1335         return 0;
1336
1337 socket_setattr_failure:
1338         kfree(buf);
1339         kfree(opt);
1340         return ret_val;
1341 }
1342
1343 /**
1344  * cipso_v4_sock_getattr - Get the security attributes from a sock
1345  * @sk: the sock
1346  * @secattr: the security attributes
1347  *
1348  * Description:
1349  * Query @sk to see if there is a CIPSO option attached to the sock and if
1350  * there is return the CIPSO security attributes in @secattr.  This function
1351  * requires that @sk be locked, or privately held, but it does not do any
1352  * locking itself.  Returns zero on success and negative values on failure.
1353  *
1354  */
1355 int cipso_v4_sock_getattr(struct sock *sk, struct netlbl_lsm_secattr *secattr)
1356 {
1357         int ret_val = -ENOMSG;
1358         struct inet_sock *sk_inet;
1359         unsigned char *cipso_ptr;
1360         u32 doi;
1361         struct cipso_v4_doi *doi_def;
1362
1363         sk_inet = inet_sk(sk);
1364         if (sk_inet->opt == NULL || sk_inet->opt->cipso == 0)
1365                 return -ENOMSG;
1366         cipso_ptr = sk_inet->opt->__data + sk_inet->opt->cipso -
1367                 sizeof(struct iphdr);
1368         ret_val = cipso_v4_cache_check(cipso_ptr, cipso_ptr[1], secattr);
1369         if (ret_val == 0)
1370                 return ret_val;
1371
1372         doi = ntohl(*(__be32 *)&cipso_ptr[2]);
1373         rcu_read_lock();
1374         doi_def = cipso_v4_doi_getdef(doi);
1375         if (doi_def == NULL) {
1376                 rcu_read_unlock();
1377                 return -ENOMSG;
1378         }
1379         switch (cipso_ptr[6]) {
1380         case CIPSO_V4_TAG_RBITMAP:
1381                 ret_val = cipso_v4_parsetag_rbm(doi_def,
1382                                                 &cipso_ptr[6],
1383                                                 secattr);
1384                 break;
1385         }
1386         rcu_read_unlock();
1387
1388         return ret_val;
1389 }
1390
1391 /**
1392  * cipso_v4_socket_getattr - Get the security attributes from a socket
1393  * @sock: the socket
1394  * @secattr: the security attributes
1395  *
1396  * Description:
1397  * Query @sock to see if there is a CIPSO option attached to the socket and if
1398  * there is return the CIPSO security attributes in @secattr.  Returns zero on
1399  * success and negative values on failure.
1400  *
1401  */
1402 int cipso_v4_socket_getattr(const struct socket *sock,
1403                             struct netlbl_lsm_secattr *secattr)
1404 {
1405         int ret_val;
1406
1407         lock_sock(sock->sk);
1408         ret_val = cipso_v4_sock_getattr(sock->sk, secattr);
1409         release_sock(sock->sk);
1410
1411         return ret_val;
1412 }
1413
1414 /**
1415  * cipso_v4_skbuff_getattr - Get the security attributes from the CIPSO option
1416  * @skb: the packet
1417  * @secattr: the security attributes
1418  *
1419  * Description:
1420  * Parse the given packet's CIPSO option and return the security attributes.
1421  * Returns zero on success and negative values on failure.
1422  *
1423  */
1424 int cipso_v4_skbuff_getattr(const struct sk_buff *skb,
1425                             struct netlbl_lsm_secattr *secattr)
1426 {
1427         int ret_val = -ENOMSG;
1428         unsigned char *cipso_ptr;
1429         u32 doi;
1430         struct cipso_v4_doi *doi_def;
1431
1432         if (!CIPSO_V4_OPTEXIST(skb))
1433                 return -ENOMSG;
1434         cipso_ptr = CIPSO_V4_OPTPTR(skb);
1435         if (cipso_v4_cache_check(cipso_ptr, cipso_ptr[1], secattr) == 0)
1436                 return 0;
1437
1438         doi = ntohl(*(__be32 *)&cipso_ptr[2]);
1439         rcu_read_lock();
1440         doi_def = cipso_v4_doi_getdef(doi);
1441         if (doi_def == NULL)
1442                 goto skbuff_getattr_return;
1443         switch (cipso_ptr[6]) {
1444         case CIPSO_V4_TAG_RBITMAP:
1445                 ret_val = cipso_v4_parsetag_rbm(doi_def,
1446                                                 &cipso_ptr[6],
1447                                                 secattr);
1448                 break;
1449         }
1450
1451 skbuff_getattr_return:
1452         rcu_read_unlock();
1453         return ret_val;
1454 }
1455
1456 /*
1457  * Setup Functions
1458  */
1459
1460 /**
1461  * cipso_v4_init - Initialize the CIPSO module
1462  *
1463  * Description:
1464  * Initialize the CIPSO module and prepare it for use.  Returns zero on success
1465  * and negative values on failure.
1466  *
1467  */
1468 static int __init cipso_v4_init(void)
1469 {
1470         int ret_val;
1471
1472         ret_val = cipso_v4_cache_init();
1473         if (ret_val != 0)
1474                 panic("Failed to initialize the CIPSO/IPv4 cache (%d)\n",
1475                       ret_val);
1476
1477         return 0;
1478 }
1479
1480 subsys_initcall(cipso_v4_init);