openafs-string-header-cleanup-20071030
[openafs.git] / src / rxkad / rxkad_server.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  * 
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 /* The rxkad security object.  Authentication using a DES-encrypted
11  * Kerberos-style ticket.  These are the server-only routines. */
12
13
14 #include <afsconfig.h>
15 #include <afs/param.h>
16
17 RCSID
18     ("$Header$");
19
20 #include <afs/stds.h>
21 #include <sys/types.h>
22 #if (defined(AFS_AIX_ENV) && defined(KERNEL) && !defined(UKERNEL)) || defined(AFS_AUX_ENV) || defined(AFS_SUN5_ENV) 
23 #include <sys/systm.h>
24 #endif
25 #include <time.h>
26 #ifdef AFS_NT40_ENV
27 #include <winsock2.h>
28 #else
29 #include <netinet/in.h>
30 #endif
31 #include <string.h>
32 #include <rx/rx.h>
33 #include <rx/xdr.h>
34 #include <des.h>
35 #include <afs/afsutil.h>
36 #include <des/stats.h>
37 #include "private_data.h"
38 #define XPRT_RXKAD_SERVER
39
40 /*
41  * This can be set to allow alternate ticket decoding.
42  * Currently only used by the AFS/DFS protocol translator to recognize
43  * Kerberos V5 tickets. The actual code to do that is provided externally.
44  */
45 afs_int32(*rxkad_AlternateTicketDecoder) ();
46
47 static struct rx_securityOps rxkad_server_ops = {
48     rxkad_Close,
49     rxkad_NewConnection,
50     rxkad_PreparePacket,        /* once per packet creation */
51     0,                          /* send packet (once per retrans) */
52     rxkad_CheckAuthentication,
53     rxkad_CreateChallenge,
54     rxkad_GetChallenge,
55     0,
56     rxkad_CheckResponse,
57     rxkad_CheckPacket,          /* check data packet */
58     rxkad_DestroyConnection,
59     rxkad_GetStats,
60     0,                          /* spare 1 */
61     0,                          /* spare 2 */
62     0,                          /* spare 3 */
63 };
64 extern afs_uint32 rx_MyMaxSendSize;
65
66 /* Miscellaneous random number routines that use the fcrypt module and the
67  * timeofday. */
68
69 static fc_KeySchedule random_int32_schedule;
70
71 #ifdef AFS_PTHREAD_ENV
72 /*
73  * This mutex protects the following global variables:
74  * random_int32_schedule
75  * seed
76  */
77
78 #include <assert.h>
79 pthread_mutex_t rxkad_random_mutex;
80 #define LOCK_RM assert(pthread_mutex_lock(&rxkad_random_mutex)==0)
81 #define UNLOCK_RM assert(pthread_mutex_unlock(&rxkad_random_mutex)==0)
82 #else
83 #define LOCK_RM
84 #define UNLOCK_RM
85 #endif /* AFS_PTHREAD_ENV */
86
87 static void
88 init_random_int32(void)
89 {
90     struct timeval key;
91
92     gettimeofday(&key, NULL);
93     LOCK_RM;
94     fc_keysched((struct ktc_encryptionKey*)&key, random_int32_schedule);
95     UNLOCK_RM;
96 }
97
98 static afs_int32
99 get_random_int32(void)
100 {
101     static struct timeval seed;
102     afs_int32 rc;
103
104     LOCK_RM;
105     fc_ecb_encrypt(&seed, &seed, random_int32_schedule, ENCRYPT);
106     rc = seed.tv_sec;
107     UNLOCK_RM;
108     return rc;
109 }
110
111 /* Called with four parameters.  The first is the level of encryption, as
112    defined in the rxkad.h file.  The second and third are a rock and a
113    procedure that is called with the key version number that accompanies the
114    ticket and returns a pointer to the server's decryption key.  The fourth
115    argument, if not NULL, is a pointer to a function that will be called for
116    every new connection with the name, instance and cell of the client.  The
117    routine should return zero if the user is NOT acceptible to the server.  If
118    this routine is not supplied, the server can call rxkad_GetServerInfo with
119    the rx connection pointer passed to the RPC routine to obtain information
120    about the client. */
121
122 /*
123   rxkad_level      level;               * minimum level *
124   char            *get_key_rock;        * rock for get_key implementor *
125   int            (*get_key)();          * passed kvno & addr(key) to fill *
126   int            (*user_ok)();          * passed name, inst, cell => bool *
127 */
128
129 struct rx_securityClass *
130 rxkad_NewServerSecurityObject(rxkad_level level, char *get_key_rock,
131                               int (*get_key) (char *get_key_rock, int kvno,
132                                               struct ktc_encryptionKey *
133                                               serverKey),
134                               int (*user_ok) (char *name, char *instance,
135                                               char *cell, afs_int32 kvno))
136 {
137     struct rx_securityClass *tsc;
138     struct rxkad_sprivate *tsp;
139     int size;
140
141     if (!get_key)
142         return 0;
143
144     size = sizeof(struct rx_securityClass);
145     tsc = (struct rx_securityClass *)osi_Alloc(size);
146     memset(tsc, 0, size);
147     tsc->refCount = 1;          /* caller has one reference */
148     tsc->ops = &rxkad_server_ops;
149     size = sizeof(struct rxkad_sprivate);
150     tsp = (struct rxkad_sprivate *)osi_Alloc(size);
151     memset(tsp, 0, size);
152     tsc->privateData = (char *)tsp;
153
154     tsp->type |= rxkad_server;  /* so can identify later */
155     tsp->level = level;         /* level of encryption */
156     tsp->get_key_rock = get_key_rock;
157     tsp->get_key = get_key;     /* to get server ticket */
158     tsp->user_ok = user_ok;     /* to inform server of client id. */
159     init_random_int32();
160
161     INC_RXKAD_STATS(serverObjects);
162     return tsc;
163 }
164
165 /* server: called to tell if a connection authenticated properly */
166
167 int
168 rxkad_CheckAuthentication(struct rx_securityClass *aobj,
169                           struct rx_connection *aconn)
170 {
171     struct rxkad_sconn *sconn;
172
173     /* first make sure the object exists */
174     if (!aconn->securityData)
175         return RXKADINCONSISTENCY;
176
177     sconn = (struct rxkad_sconn *)aconn->securityData;
178     return !sconn->authenticated;
179 }
180
181 /* server: put the current challenge in the connection structure for later use
182    by packet sender */
183
184 int
185 rxkad_CreateChallenge(struct rx_securityClass *aobj,
186                       struct rx_connection *aconn)
187 {
188     struct rxkad_sconn *sconn;
189     struct rxkad_sprivate *tsp;
190
191     sconn = (struct rxkad_sconn *)aconn->securityData;
192     sconn->challengeID = get_random_int32();
193     sconn->authenticated = 0;   /* conn unauth. 'til we hear back */
194     /* initialize level from object's minimum acceptable level */
195     tsp = (struct rxkad_sprivate *)aobj->privateData;
196     sconn->level = tsp->level;
197     return 0;
198 }
199
200 /* server: fill in a challenge in the packet */
201
202 int
203 rxkad_GetChallenge(struct rx_securityClass *aobj, struct rx_connection *aconn,
204                    struct rx_packet *apacket)
205 {
206     struct rxkad_sconn *sconn;
207     char *challenge;
208     int challengeSize;
209     struct rxkad_v2Challenge c_v2;      /* version 2 */
210     struct rxkad_oldChallenge c_old;    /* old style */
211
212     sconn = (struct rxkad_sconn *)aconn->securityData;
213     if (rx_IsUsingPktCksum(aconn))
214         sconn->cksumSeen = 1;
215
216     if (sconn->cksumSeen) {
217         memset(&c_v2, 0, sizeof(c_v2));
218         c_v2.version = htonl(RXKAD_CHALLENGE_PROTOCOL_VERSION);
219         c_v2.challengeID = htonl(sconn->challengeID);
220         c_v2.level = htonl((afs_int32) sconn->level);
221         c_v2.spare = 0;
222         challenge = (char *)&c_v2;
223         challengeSize = sizeof(c_v2);
224     } else {
225         memset(&c_old, 0, sizeof(c_old));
226         c_old.challengeID = htonl(sconn->challengeID);
227         c_old.level = htonl((afs_int32) sconn->level);
228         challenge = (char *)&c_old;
229         challengeSize = sizeof(c_old);
230     }
231     if (rx_MyMaxSendSize < challengeSize)
232         return RXKADPACKETSHORT;        /* not enough space */
233
234     rx_packetwrite(apacket, 0, challengeSize, challenge);
235     rx_SetDataSize(apacket, challengeSize);
236     sconn->tried = 1;
237     INC_RXKAD_STATS(challengesSent);
238     return 0;
239 }
240
241 /* server: process a response to a challenge packet */
242 /* XXX this does some copying of data in and out of the packet, but I'll bet it
243  * could just do it in place, especially if I used rx_Pullup...
244  */
245 int
246 rxkad_CheckResponse(struct rx_securityClass *aobj,
247                     struct rx_connection *aconn, struct rx_packet *apacket)
248 {
249     struct rxkad_sconn *sconn;
250     struct rxkad_sprivate *tsp;
251     struct ktc_encryptionKey serverKey;
252     struct rxkad_oldChallengeResponse oldr;     /* response format */
253     struct rxkad_v2ChallengeResponse v2r;
254     afs_int32 tlen;             /* ticket len */
255     afs_int32 kvno;             /* key version of ticket */
256     char tix[MAXKTCTICKETLEN];
257     afs_int32 incChallengeID;
258     rxkad_level level;
259     int code;
260     /* ticket contents */
261     struct ktc_principal client;
262     struct ktc_encryptionKey sessionkey;
263     afs_int32 host;
264     afs_uint32 start;
265     afs_uint32 end;
266     unsigned int pos;
267     struct rxkad_serverinfo *rock;
268
269     sconn = (struct rxkad_sconn *)aconn->securityData;
270     tsp = (struct rxkad_sprivate *)aobj->privateData;
271
272     if (sconn->cksumSeen) {
273         /* expect v2 response, leave fields in v2r in network order for cksum
274          * computation which follows decryption. */
275         if (rx_GetDataSize(apacket) < sizeof(v2r))
276             return RXKADPACKETSHORT;
277         rx_packetread(apacket, 0, sizeof(v2r), &v2r);
278         pos = sizeof(v2r);
279         /* version == 2 */
280         /* ignore spare */
281         kvno = ntohl(v2r.kvno);
282         tlen = ntohl(v2r.ticketLen);
283         if (rx_GetDataSize(apacket) < sizeof(v2r) + tlen)
284             return RXKADPACKETSHORT;
285     } else {
286         /* expect old format response */
287         if (rx_GetDataSize(apacket) < sizeof(oldr))
288             return RXKADPACKETSHORT;
289         rx_packetread(apacket, 0, sizeof(oldr), &oldr);
290         pos = sizeof(oldr);
291
292         kvno = ntohl(oldr.kvno);
293         tlen = ntohl(oldr.ticketLen);
294         if (rx_GetDataSize(apacket) != sizeof(oldr) + tlen)
295             return RXKADPACKETSHORT;
296     }
297     if ((tlen < MINKTCTICKETLEN) || (tlen > MAXKTCTICKETLEN))
298         return RXKADTICKETLEN;
299
300     rx_packetread(apacket, pos, tlen, tix);     /* get ticket */
301
302     /*
303      * We allow the ticket to be optionally decoded by an alternate
304      * ticket decoder, if the function variable
305      * rxkad_AlternateTicketDecoder is set. That function should
306      * return a code of -1 if it wants the ticket to be decoded by
307      * the standard decoder.
308      */
309     if (rxkad_AlternateTicketDecoder) {
310         code =
311             rxkad_AlternateTicketDecoder(kvno, tix, tlen, client.name,
312                                          client.instance, client.cell,
313                                          &sessionkey, &host, &start, &end);
314         if (code && code != -1) {
315             return code;
316         }
317     } else {
318         code = -1;              /* No alternate ticket decoder present */
319     }
320
321     /*
322      * If the alternate decoder is not present, or returns -1, then
323      * assume the ticket is of the default style.
324      */
325     if (code == -1 && ((kvno == RXKAD_TKT_TYPE_KERBEROS_V5)
326         || (kvno == RXKAD_TKT_TYPE_KERBEROS_V5_ENCPART_ONLY))) {
327         code =
328             tkt_DecodeTicket5(tix, tlen, tsp->get_key, tsp->get_key_rock,
329                               kvno, client.name, client.instance, client.cell,
330                               &sessionkey, &host, &start, &end);
331         if (code)
332             return code;
333     }
334
335     /*
336      * If the alternate decoder/kerberos 5 decoder is not present, or
337      * returns -1, then assume the ticket is of the default style.
338      */
339     if (code == -1) {
340         /* get ticket's key */
341         code = (*tsp->get_key) (tsp->get_key_rock, kvno, &serverKey);
342         if (code)
343             return RXKADUNKNOWNKEY;     /* invalid kvno */
344         code =
345             tkt_DecodeTicket(tix, tlen, &serverKey, client.name,
346                              client.instance, client.cell, &sessionkey, &host,
347                              &start, &end);
348         if (code)
349             return code;
350     }
351     code = tkt_CheckTimes(start, end, time(0));
352     if (code == 0) 
353         return RXKADNOAUTH;
354     else if (code == -1)
355         return RXKADEXPIRED;
356     else if (code < -1)
357         return RXKADBADTICKET;
358
359     code = fc_keysched(&sessionkey, sconn->keysched);
360     if (code)
361         return RXKADBADKEY;
362     memcpy(sconn->ivec, &sessionkey, sizeof(sconn->ivec));
363
364     if (sconn->cksumSeen) {
365         /* using v2 response */
366         afs_uint32 cksum;       /* observed cksum */
367         struct rxkad_endpoint endpoint; /* connections endpoint */
368         int i;
369         afs_uint32 xor[2];
370
371         memcpy(xor, sconn->ivec, 2 * sizeof(afs_int32));
372         fc_cbc_encrypt(&v2r.encrypted, &v2r.encrypted, sizeof(v2r.encrypted),
373                        sconn->keysched, xor, DECRYPT);
374         cksum = rxkad_CksumChallengeResponse(&v2r);
375         if (cksum != v2r.encrypted.endpoint.cksum)
376             return RXKADSEALEDINCON;
377         (void)rxkad_SetupEndpoint(aconn, &endpoint);
378         v2r.encrypted.endpoint.cksum = 0;
379         if (memcmp(&endpoint, &v2r.encrypted.endpoint, sizeof(endpoint)) != 0)
380             return RXKADSEALEDINCON;
381         for (i = 0; i < RX_MAXCALLS; i++) {
382             v2r.encrypted.callNumbers[i] =
383                 ntohl(v2r.encrypted.callNumbers[i]);
384             if (v2r.encrypted.callNumbers[i] < 0)
385                 return RXKADSEALEDINCON;
386         }
387
388         (void)rxi_SetCallNumberVector(aconn, v2r.encrypted.callNumbers);
389         incChallengeID = ntohl(v2r.encrypted.incChallengeID);
390         level = ntohl(v2r.encrypted.level);
391     } else {
392         /* expect old format response */
393         fc_ecb_encrypt(&oldr.encrypted, &oldr.encrypted, sconn->keysched,
394                        DECRYPT);
395         incChallengeID = ntohl(oldr.encrypted.incChallengeID);
396         level = ntohl(oldr.encrypted.level);
397     }
398     if (incChallengeID != sconn->challengeID + 1)
399         return RXKADOUTOFSEQUENCE;      /* replay attempt */
400     if ((level < sconn->level) || (level > rxkad_crypt))
401         return RXKADLEVELFAIL;
402     sconn->level = level;
403     rxkad_SetLevel(aconn, sconn->level);
404     INC_RXKAD_STATS(responses[rxkad_LevelIndex(sconn->level)]);
405     /* now compute endpoint-specific info used for computing 16 bit checksum */
406     rxkad_DeriveXORInfo(aconn, sconn->keysched, sconn->ivec, sconn->preSeq);
407
408     /* otherwise things are ok */
409     sconn->expirationTime = end;
410     sconn->authenticated = 1;
411
412     if (tsp->user_ok) {
413         code = tsp->user_ok(client.name, client.instance, client.cell, kvno);
414         if (code)
415             return RXKADNOAUTH;
416     } else {                    /* save the info for later retreival */
417         int size = sizeof(struct rxkad_serverinfo);
418         rock = (struct rxkad_serverinfo *)osi_Alloc(size);
419         memset(rock, 0, size);
420         rock->kvno = kvno;
421         memcpy(&rock->client, &client, sizeof(rock->client));
422         sconn->rock = rock;
423     }
424     return 0;
425 }
426
427 /* return useful authentication info about a server-side connection */
428
429 afs_int32
430 rxkad_GetServerInfo(struct rx_connection * aconn, rxkad_level * level,
431                     afs_uint32 * expiration, char *name, char *instance,
432                     char *cell, afs_int32 * kvno)
433 {
434     struct rxkad_sconn *sconn;
435
436     sconn = (struct rxkad_sconn *)aconn->securityData;
437     if (sconn && sconn->authenticated && sconn->rock
438         && (time(0) < sconn->expirationTime)) {
439         if (level)
440             *level = sconn->level;
441         if (expiration)
442             *expiration = sconn->expirationTime;
443         if (name)
444             strcpy(name, sconn->rock->client.name);
445         if (instance)
446             strcpy(instance, sconn->rock->client.instance);
447         if (cell)
448             strcpy(cell, sconn->rock->client.cell);
449         if (kvno)
450             *kvno = sconn->rock->kvno;
451         return 0;
452     } else
453         return RXKADNOAUTH;
454 }