xref: /plan9/sys/src/cmd/ssh2/cipheraes.c (revision 63afb9a5d3f910047231762bcce0ee49fed3d07c)
1 #include <u.h>
2 #include <libc.h>
3 #include <mp.h>
4 #include <fcall.h>
5 #include <thread.h>
6 #include <9p.h>
7 #include <libsec.h>
8 #include "netssh.h"
9 
10 static QLock aeslock;
11 
12 struct CipherState {
13 	AESstate state;
14 };
15 
16 static CipherState *
initaes(Conn * c,int dir,int bits)17 initaes(Conn *c, int dir, int bits)
18 {
19 	CipherState *cs;
20 
21 	qlock(&aeslock);
22 	cs = emalloc9p(sizeof(CipherState));
23 	if(dir)
24 		setupAESstate(&cs->state, c->s2cek, bits/8, c->s2civ);
25 	else
26 		setupAESstate(&cs->state, c->c2sek, bits/8, c->c2siv);
27 	qunlock(&aeslock);
28 	return cs;
29 }
30 
31 static CipherState*
initaes128(Conn * c,int dir)32 initaes128(Conn *c, int dir)
33 {
34 	return initaes(c, dir, 128);
35 }
36 
37 static CipherState*
initaes192(Conn * c,int dir)38 initaes192(Conn *c, int dir)
39 {
40 	return initaes(c, dir, 192);
41 }
42 
43 static CipherState*
initaes256(Conn * c,int dir)44 initaes256(Conn *c, int dir)
45 {
46 	return initaes(c, dir, 256);
47 }
48 
49 static void
encryptaes(CipherState * cs,uchar * buf,int nbuf)50 encryptaes(CipherState *cs, uchar *buf, int nbuf)
51 {
52 	if(cs->state.setup != 0xcafebabe || cs->state.rounds > AESmaxrounds)
53 		return;
54 	qlock(&aeslock);
55 	aesCBCencrypt(buf, nbuf, &cs->state);
56 	qunlock(&aeslock);
57 }
58 
59 static void
decryptaes(CipherState * cs,uchar * buf,int nbuf)60 decryptaes(CipherState *cs, uchar *buf, int nbuf)
61 {
62 	if(cs->state.setup != 0xcafebabe || cs->state.rounds > AESmaxrounds)
63 		return;
64 	qlock(&aeslock);
65 	aesCBCdecrypt(buf, nbuf, &cs->state);
66 	qunlock(&aeslock);
67 }
68 
69 Cipher cipheraes128 = {
70 	"aes128-cbc",
71 	AESbsize,
72 	initaes128,
73 	encryptaes,
74 	decryptaes,
75 };
76 
77 Cipher cipheraes192 = {
78 	"aes192-cbc",
79 	AESbsize,
80 	initaes192,
81 	encryptaes,
82 	decryptaes,
83 };
84 
85 Cipher cipheraes256 = {
86 	"aes256-cbc",
87 	AESbsize,
88 	initaes256,
89 	encryptaes,
90 	decryptaes,
91 };
92