summaryrefslogtreecommitdiffstats
path: root/README.ASN1
blob: 11bcfaf4ddb258bf4da41bae2160be053648c01d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
OpenSSL ASN1 Revision
=====================

This document describes some of the issues relating to the new ASN1 code.

Previous OpenSSL ASN1 problems
=============================

OK why did the OpenSSL ASN1 code need revising in the first place? Well
there are lots of reasons some of which are included below...

1. The code is difficult to read and write. For every single ASN1 structure
(e.g. SEQUENCE) four functions need to be written for new, free, encode and
decode operations. This is a very painful and error prone operation. Very few
people have ever written any OpenSSL ASN1 and those that have usually wish
they hadn't.

2. Partly because of 1. the code is bloated and takes up a disproportionate
amount of space. The SEQUENCE encoder is particularly bad: it essentially
contains two copies of the same operation, one to compute the SEQUENCE length
and the other to encode it.

3. The code is memory based: that is it expects to be able to read the whole
structure from memory. This is fine for small structures but if you have a
(say) 1Gb PKCS#7 signedData structure it isn't such a good idea...

4. The code for the ASN1 IMPLICIT tag is evil. It is handled by temporarily
changing the tag to the expected one, attempting to read it, then changing it
back again. This means that decode buffers have to be writable even though they
are ultimately unchanged. This gets in the way of constification.

5. The handling of EXPLICIT isn't much better. It adds a chunk of code into 
the decoder and encoder for every EXPLICIT tag.

6. APPLICATION and PRIVATE tags aren't even supported at all.

7. Even IMPLICIT isn't complete: there is no support for implicitly tagged
types that are not OPTIONAL.

8. Much of the code assumes that a tag will fit in a single octet. This is
only true if the tag is 30 or less (mercifully tags over 30 are rare).

9. The ASN1 CHOICE type has to be largely handled manually, there aren't any
macros that properly support it.

10. Encoders have no concept of OPTIONAL and have no error checking. If the
passed structure contains a NULL in a mandatory field it will not be encoded,
resulting in an invalid structure.

11. It is tricky to add ASN1 encoders and decoders to external applications.

Template model
==============

One of the major problems with revision is the sheer volume of the ASN1 code.
Attempts to change (for example) the IMPLICIT behaviour would result in a
modification of *every* single decode function. 

I decided to adopt a template based approach. I'm using the term 'template'
in a manner similar to SNACC templates: it has nothing to do with C++
templates.

A template is a description of an ASN1 module as several constant C structures.
It describes in a machine readable way exactly how the ASN1 structure should
behave. If this template contains enough detail then it is possible to write
versions of new, free, encode, decode (and possibly others operations) that
operate on templates.

Instead of having to write code to handle each operation only a single
template needs to be written. If new operations are needed (such as a 'print'
operation) only a single new template based function needs to be written 
which will then automatically handle all existing templates.

Plans for revision
==================

The revision will consist of the following steps. Other than the first two
these can be handled in any order.
 
o Design and write template new, free, encode and decode operations, initially
memory based. *DONE*

o Convert existing ASN1 code to template form. *IN PROGRESS*

o Convert an existing ASN1 compiler (probably SNACC) to output templates
in OpenSSL form.

o Add support for BIO based ASN1 encoders and decoders to handle large
structures, initially blocking I/O.

o Add support for non blocking I/O: this is quite a bit harder than blocking
I/O.

o Add new ASN1 structures, such as OCSP, CRMF, S/MIME v3 (CMS), attribute
certificates etc etc.

Description of major changes
============================

The BOOLEAN type now takes three values. 0xff is TRUE, 0 is FALSE and -1 is
absent. The meaning of absent depends on the context. If for example the
boolean type is DEFAULT FALSE (as in the case of the critical flag for
certificate extensions) then -1 is FALSE, if DEFAULT TRUE then -1 is TRUE.
Usually the value will only ever be read via an API which will hide this from
an application.

There is an evil bug in the old ASN1 code that mishandles OPTIONAL with
SEQUENCE OF or SET OF. These are both implemented as a STACK structure. The
old code would omit the structure if the STACK was NULL (which is fine) or if
it had zero elements (which is NOT OK). This causes problems because an empty
SEQUENCE OF or SET OF will result in an empty STACK when it is decoded but when
it is encoded it will be omitted resulting in different encodings. The new code
only omits the encoding if the STACK is NULL, if it contains zero elements it
is encoded and empty. There is an additional problem though: because an empty
STACK was omitted, sometimes the corresponding *_new() function would
initialize the STACK to empty so an application could immediately use it, if
this is done with the new code (i.e. a NULL) it wont work. Therefore a new
STACK should be allocated first. One instance of this is the X509_CRL list of
revoked certificates: a helper function X509_CRL_add0_revoked() has been added
for this purpose.

The X509_ATTRIBUTE structure used to have an element called 'set' which took
the value 1 if the attribute value was a SET OF or 0 if it was a single. Due
to the behaviour of CHOICE in the new code this has been changed to a field
called 'single' which is 0 for a SET OF and 1 for single. The old field has
been deleted to deliberately break source compatibility. Since this structure
is normally accessed via higher level functions this shouldn't break too much.

The X509_REQ_INFO certificate request info structure no longer has a field
called 'req_kludge'. This used to be set to 1 if the attributes field was
(incorrectly) omitted. You can check to see if the field is omitted now by
checking if the attributes field is NULL. Similarly if you need to omit
the field then free attributes and set it to NULL.

The top level 'detached' field in the PKCS7 structure is no longer set when
a PKCS#7 structure is read in. PKCS7_is_detached() should be called instead.
The behaviour of PKCS7_get_detached() is unaffected.

The values of 'type' in the GENERAL_NAME structure have changed. This is
because the old code use the ASN1 initial octet as the selector. The new
code uses the index in the ASN1_CHOICE template.

The DIST_POINT_NAME structure has changed to be a true CHOICE type.

typedef struct DIST_POINT_NAME_st {
int type;
union {
	STACK_OF(GENERAL_NAME) *fullname;
	STACK_OF(X509_NAME_ENTRY) *relativename;
} name;
} DIST_POINT_NAME;

This means that name.fullname or name.relativename should be set
and type reflects the option. That is if name.fullname is set then
type is 0 and if name.relativename is set type is 1.

With the old code using the i2d functions would typically involve:

unsigned char *buf, *p;
int len;
/* Find length of encoding */
len = i2d_SOMETHING(x, NULL);
/* Allocate buffer */
buf = OPENSSL_malloc(len);
if(buf == NULL) {
	/* Malloc error */
}
/* Use temp variable because &p gets updated to point to end of
 * encoding.
 */
p = buf;
i2d_SOMETHING(x, &p);


Using the new i2d you can also do:

unsigned char *buf = NULL;
int len;
len = i2d_SOMETHING(x, &buf);
if(len < 0) {
	/* Malloc error */
}

and it will automatically allocate and populate a buffer with the
encoding. After this call 'buf' will point to the start of the
encoding which is len bytes long.
/a> 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
/* Task credentials management - see Documentation/security/credentials.txt
 *
 * Copyright (C) 2008 Red Hat, Inc. All Rights Reserved.
 * Written by David Howells (dhowells@redhat.com)
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public Licence
 * as published by the Free Software Foundation; either version
 * 2 of the Licence, or (at your option) any later version.
 */
#include <linux/export.h>
#include <linux/cred.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/key.h>
#include <linux/keyctl.h>
#include <linux/init_task.h>
#include <linux/security.h>
#include <linux/binfmts.h>
#include <linux/cn_proc.h>

#if 0
#define kdebug(FMT, ...) \
	printk("[%-5.5s%5u] "FMT"\n", current->comm, current->pid ,##__VA_ARGS__)
#else
#define kdebug(FMT, ...) \
	no_printk("[%-5.5s%5u] "FMT"\n", current->comm, current->pid ,##__VA_ARGS__)
#endif

static struct kmem_cache *cred_jar;

/*
 * The initial credentials for the initial task
 */
struct cred init_cred = {
	.usage			= ATOMIC_INIT(4),
#ifdef CONFIG_DEBUG_CREDENTIALS
	.subscribers		= ATOMIC_INIT(2),
	.magic			= CRED_MAGIC,
#endif
	.uid			= GLOBAL_ROOT_UID,
	.gid			= GLOBAL_ROOT_GID,
	.suid			= GLOBAL_ROOT_UID,
	.sgid			= GLOBAL_ROOT_GID,
	.euid			= GLOBAL_ROOT_UID,
	.egid			= GLOBAL_ROOT_GID,
	.fsuid			= GLOBAL_ROOT_UID,
	.fsgid			= GLOBAL_ROOT_GID,
	.securebits		= SECUREBITS_DEFAULT,
	.cap_inheritable	= CAP_EMPTY_SET,
	.cap_permitted		= CAP_FULL_SET,
	.cap_effective		= CAP_FULL_SET,
	.cap_bset		= CAP_FULL_SET,
	.user			= INIT_USER,
	.user_ns		= &init_user_ns,
	.group_info		= &init_groups,
};

static inline void set_cred_subscribers(struct cred *cred, int n)
{
#ifdef CONFIG_DEBUG_CREDENTIALS
	atomic_set(&cred->subscribers, n);
#endif
}

static inline int read_cred_subscribers(const struct cred *cred)
{
#ifdef CONFIG_DEBUG_CREDENTIALS
	return atomic_read(&cred->subscribers);
#else
	return 0;
#endif
}

static inline void alter_cred_subscribers(const struct cred *_cred, int n)
{
#ifdef CONFIG_DEBUG_CREDENTIALS
	struct cred *cred = (struct cred *) _cred;

	atomic_add(n, &cred->subscribers);
#endif
}

/*
 * The RCU callback to actually dispose of a set of credentials
 */
static void put_cred_rcu(struct rcu_head *rcu)
{
	struct cred *cred = container_of(rcu, struct cred, rcu);

	kdebug("put_cred_rcu(%p)", cred);

#ifdef CONFIG_DEBUG_CREDENTIALS
	if (cred->magic != CRED_MAGIC_DEAD ||
	    atomic_read(&cred->usage) != 0 ||
	    read_cred_subscribers(cred) != 0)
		panic("CRED: put_cred_rcu() sees %p with"
		      " mag %x, put %p, usage %d, subscr %d\n",
		      cred, cred->magic, cred->put_addr,
		      atomic_read(&cred->usage),
		      read_cred_subscribers(cred));
#else
	if (atomic_read(&cred->usage) != 0)
		panic("CRED: put_cred_rcu() sees %p with usage %d\n",
		      cred, atomic_read(&cred->usage));
#endif

	security_cred_free(cred);
	key_put(cred->session_keyring);
	key_put(cred->process_keyring);
	key_put(cred->thread_keyring);
	key_put(cred->request_key_auth);
	if (cred->group_info)
		put_group_info(cred->group_info);
	free_uid(cred->user);
	put_user_ns(cred->user_ns);
	kmem_cache_free(cred_jar, cred);
}

/**
 * __put_cred - Destroy a set of credentials
 * @cred: The record to release
 *
 * Destroy a set of credentials on which no references remain.
 */
void __put_cred(struct cred *cred)
{
	kdebug("__put_cred(%p{%d,%d})", cred,
	       atomic_read(&cred->usage),
	       read_cred_subscribers(cred));

	BUG_ON(atomic_read(&cred->usage) != 0);
#ifdef CONFIG_DEBUG_CREDENTIALS
	BUG_ON(read_cred_subscribers(cred) != 0);
	cred->magic = CRED_MAGIC_DEAD;
	cred->put_addr = __builtin_return_address(0);
#endif
	BUG_ON(cred == current->cred);
	BUG_ON(cred == current->real_cred);

	call_rcu(&cred->rcu, put_cred_rcu);
}
EXPORT_SYMBOL(__put_cred);

/*
 * Clean up a task's credentials when it exits
 */
void exit_creds(struct task_struct *tsk)
{
	struct cred *cred;

	kdebug("exit_creds(%u,%p,%p,{%d,%d})", tsk->pid, tsk->real_cred, tsk->cred,
	       atomic_read(&tsk->cred->usage),
	       read_cred_subscribers(tsk->cred));

	cred = (struct cred *) tsk->real_cred;
	tsk->real_cred = NULL;
	validate_creds(cred);
	alter_cred_subscribers(cred, -1);
	put_cred(cred);

	cred = (struct cred *) tsk->cred;
	tsk->cred = NULL;
	validate_creds(cred);
	alter_cred_subscribers(cred, -1);
	put_cred(cred);
}

/**
 * get_task_cred - Get another task's objective credentials
 * @task: The task to query
 *
 * Get the objective credentials of a task, pinning them so that they can't go
 * away.  Accessing a task's credentials directly is not permitted.
 *
 * The caller must also make sure task doesn't get deleted, either by holding a
 * ref on task or by holding tasklist_lock to prevent it from being unlinked.
 */
const struct cred *get_task_cred(struct task_struct *task)
{
	const struct cred *cred;

	rcu_read_lock();

	do {
		cred = __task_cred((task));
		BUG_ON(!cred);
	} while (!atomic_inc_not_zero(&((struct cred *)cred)->usage));

	rcu_read_unlock();
	return cred;
}

/*
 * Allocate blank credentials, such that the credentials can be filled in at a
 * later date without risk of ENOMEM.
 */
struct cred *cred_alloc_blank(void)
{
	struct cred *new;

	new = kmem_cache_zalloc(cred_jar, GFP_KERNEL);
	if (!new)
		return NULL;

	atomic_set(&new->usage, 1);
#ifdef CONFIG_DEBUG_CREDENTIALS
	new->magic = CRED_MAGIC;
#endif

	if (security_cred_alloc_blank(new,