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