aboutsummaryrefslogtreecommitdiff
path: root/src/cmd/auth/factotum/dsa.c
blob: c0d199e412f7e5a25b1b312fb31693e6f0482ab9 (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
#include "std.h"
#include "dat.h"

/*
 * DSA signing and verification
 * 
 * Sign:
 *	start p=xxx q=xxx alpha=xxx key=xxx
 *	write msg
 *	read signature(msg)
 *
 * Verify: (not implemented)
 *	start p=xxx q=xxx alpha=xxx key=xxx
 *	write msg
 *	write signature(msg)
 *	read ok or fail
 * 
 * all numbers are hexadecimal bigints parsable with strtomp.
 */
 
static int
xdsasign(Conv *c)
{
	int n;
	mpint *m;
	uchar digest[SHA1dlen], sigblob[20+20];
	DSAsig *sig;
	Key *k;

	k = keylookup("%A", c->attr);
	if(k == nil)
		return -1;

	c->state = "read data";
	if((n=convread(c, digest, SHA1dlen)) < 0){
		keyclose(k);
		return -1;
	}
	m = betomp(digest, SHA1dlen, nil);
	if(m == nil){
		keyclose(k);
		return -1;
	}
	sig = dsasign(k->priv, m);
	keyclose(k);
	mpfree(m);
	if(sig == nil)
		return -1;
	if(mpsignif(sig->r) > 20*8 || mpsignif(sig->s) > 20*8){
		werrstr("signature too long");
		return -1;
	}
	mptoberjust(sig->r, sigblob, 20);
	mptoberjust(sig->s, sigblob+20, 20);
	convwrite(c, sigblob, sizeof sigblob);
	dsasigfree(sig);
	return 0;
}

/*
 * convert to canonical form (lower case) 
 * for use in attribute matches.
 */
static void
strlwr(char *a)
{
	for(; *a; a++){
		if('A' <= *a && *a <= 'Z')
			*a += 'a' - 'A';
	}
}

static DSApriv*
readdsapriv(Key *k)
{
	char *a;
	DSApriv *priv;

	priv = dsaprivalloc();

	if((a=strfindattr(k->attr, "p"))==nil 
	|| (priv->pub.p=strtomp(a, nil, 16, nil))==nil)
		goto Error;
	strlwr(a);
	if((a=strfindattr(k->attr, "q"))==nil 
	|| (priv->pub.q=strtomp(a, nil, 16, nil))==nil)
		goto Error;
	strlwr(a);
	if((a=strfindattr(k->attr, "alpha"))==nil 
	|| (priv->pub.alpha=strtomp(a, nil, 16, nil))==nil)
		goto Error;
	strlwr(a);
	if((a=strfindattr(k->attr, "key"))==nil 
	|| (priv->pub.key=strtomp(a, nil, 16, nil))==nil)
		goto Error;
	strlwr(a);
	if((a=strfindattr(k->privattr, "!secret"))==nil 
	|| (priv->secret=strtomp(a, nil, 16, nil))==nil)
		goto Error;
	strlwr(a);
	return priv;

Error:
	dsaprivfree(priv);
	return nil;
}

static int
dsacheck(Key *k)
{
	static int first = 1;
	
	if(first){
		fmtinstall('B', mpfmt);
		first = 0;
	}

	if((k->priv = readdsapriv(k)) == nil){
		werrstr("malformed key data");
		return -1;
	}
	return 0;
}

static void
dsaclose(Key *k)
{
	dsaprivfree(k->priv);
	k->priv = nil;
}

static Role
dsaroles[] = 
{
	"sign",	xdsasign,
	0
};

Proto dsa = {
	"dsa",
	dsaroles,
	nil,
	dsacheck,
	dsaclose
};