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
encryptaesctr(CipherState * cs,uchar * buf,int nbuf)60 encryptaesctr(CipherState *cs, uchar *buf, int nbuf)
61 {
62 if(cs->state.setup != 0xcafebabe || cs->state.rounds > AESmaxrounds)
63 return;
64 qlock(&aeslock);
65 aesCTRencrypt(buf, nbuf, &cs->state);
66 qunlock(&aeslock);
67 }
68
69 static void
decryptaes(CipherState * cs,uchar * buf,int nbuf)70 decryptaes(CipherState *cs, uchar *buf, int nbuf)
71 {
72 if(cs->state.setup != 0xcafebabe || cs->state.rounds > AESmaxrounds)
73 return;
74 qlock(&aeslock);
75 aesCBCdecrypt(buf, nbuf, &cs->state);
76 qunlock(&aeslock);
77 }
78
79 static void
decryptaesctr(CipherState * cs,uchar * buf,int nbuf)80 decryptaesctr(CipherState *cs, uchar *buf, int nbuf)
81 {
82 if(cs->state.setup != 0xcafebabe || cs->state.rounds > AESmaxrounds)
83 return;
84 qlock(&aeslock);
85 aesCTRdecrypt(buf, nbuf, &cs->state);
86 qunlock(&aeslock);
87 }
88
89 Cipher cipheraes128 = {
90 "aes128-cbc",
91 AESbsize,
92 initaes128,
93 encryptaes,
94 decryptaes,
95 };
96
97 Cipher cipheraes128ctr = {
98 "aes128-ctr",
99 AESbsize,
100 initaes128,
101 encryptaesctr,
102 decryptaesctr,
103 };
104
105 Cipher cipheraes192 = {
106 "aes192-cbc",
107 AESbsize,
108 initaes192,
109 encryptaes,
110 decryptaes,
111 };
112
113 Cipher cipheraes192ctr = {
114 "aes192-ctr",
115 AESbsize,
116 initaes192,
117 encryptaesctr,
118 decryptaesctr,
119 };
120
121 Cipher cipheraes256 = {
122 "aes256-cbc",
123 AESbsize,
124 initaes256,
125 encryptaes,
126 decryptaes,
127 };
128
129 Cipher cipheraes256ctr = {
130 "aes256-ctr",
131 AESbsize,
132 initaes256,
133 encryptaesctr,
134 decryptaesctr,
135 };
136