]> Pileus Git - ~andy/fetchmail/blob - imap.c
Ready to send this to Mike.
[~andy/fetchmail] / imap.c
1 /*
2  * imap.c -- IMAP2bis/IMAP4 protocol methods
3  *
4  * Copyright 1997 by Eric S. Raymond
5  * For license terms, see the file COPYING in this directory.
6  */
7
8 #include  "config.h"
9 #include  <stdio.h>
10 #include  <string.h>
11 #include  <ctype.h>
12 #if defined(STDC_HEADERS)
13 #include  <stdlib.h>
14 #endif
15 #include  "fetchmail.h"
16 #include  "socket.h"
17
18 #ifdef KERBEROS_V4
19 #ifdef KERBEROS_V5
20 #include <kerberosIV/des.h>
21 #include <kerberosIV/krb.h>
22 #else
23 #if defined (__bsdi__)
24 #include <des.h>
25 #define krb_get_err_text(e) (krb_err_txt[e])
26 #endif
27 #if defined(__NetBSD__) || (__FreeBSD__) || defined(__linux__)
28 #define krb_get_err_text(e) (krb_err_txt[e])
29 #endif
30 #include <krb.h>
31 #endif
32 #endif /* KERBEROS_V4 */
33 #include  "i18n.h"
34
35 #ifdef GSSAPI
36 #ifdef HAVE_GSSAPI_H
37 #include <gssapi.h>
38 #endif
39 #ifdef HAVE_GSSAPI_GSSAPI_H
40 #include <gssapi/gssapi.h>
41 #endif
42 #ifdef HAVE_GSSAPI_GSSAPI_GENERIC_H
43 #include <gssapi/gssapi_generic.h>
44 #endif
45 #ifndef HAVE_GSS_C_NT_HOSTBASED_SERVICE
46 #define GSS_C_NT_HOSTBASED_SERVICE gss_nt_service_name
47 #endif
48 #endif
49
50 #include "md5.h"
51
52 #if OPIE_ENABLE
53 #include <opie.h>
54 #endif /* OPIE_ENABLE */
55
56 #ifndef strstr          /* glibc-2.1 declares this as a macro */
57 extern char *strstr();  /* needed on sysV68 R3V7.1. */
58 #endif /* strstr */
59
60 /* imap_version values */
61 #define IMAP2           -1      /* IMAP2 or IMAP2BIS, RFC1176 */
62 #define IMAP4           0       /* IMAP4 rev 0, RFC1730 */
63 #define IMAP4rev1       1       /* IMAP4 rev 1, RFC2060 */
64
65 static int count, seen, recent, unseen, deletions, imap_version, preauth; 
66 static int expunged, expunge_period;
67 static char capabilities[MSGBUFSIZE+1];
68
69 int imap_ok(int sock, char *argbuf)
70 /* parse command response */
71 {
72     char buf [MSGBUFSIZE+1];
73
74     seen = 0;
75     do {
76         int     ok;
77         char    *cp;
78
79         if ((ok = gen_recv(sock, buf, sizeof(buf))))
80             return(ok);
81
82         /* all tokens in responses are caseblind */
83         for (cp = buf; *cp; cp++)
84             if (islower(*cp))
85                 *cp = toupper(*cp);
86
87         /* interpret untagged status responses */
88         if (strstr(buf, "* CAPABILITY"))
89             strncpy(capabilities, buf + 12, sizeof(capabilities));
90         if (strstr(buf, "EXISTS"))
91             count = atoi(buf+2);
92         if (strstr(buf, "RECENT"))
93             recent = atoi(buf+2);
94         if (strstr(buf, "UNSEEN"))
95         {
96             char        *cp;
97
98             /*
99              * Handle both "* 42 UNSEEN" (if tha ever happens) and 
100              * "* OK [UNSEEN 42] 42". Note that what this gets us is
101              * a minimum index, not a count.
102              */
103             unseen = 0;
104             for (cp = buf; *cp && !isdigit(*cp); cp++)
105                 continue;
106             unseen = atoi(cp);
107         }
108         if (strstr(buf, "FLAGS"))
109             seen = (strstr(buf, "SEEN") != (char *)NULL);
110     } while
111         (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
112
113     if (tag[0] == '\0')
114     {
115         if (argbuf)
116             strcpy(argbuf, buf);
117         return(PS_SUCCESS); 
118     }
119     else
120     {
121         char    *cp;
122
123         /* skip the tag */
124         for (cp = buf; !isspace(*cp); cp++)
125             continue;
126         while (isspace(*cp))
127             cp++;
128
129         if (strncmp(cp, "PREAUTH", 2) == 0)
130         {
131             if (argbuf)
132                 strcpy(argbuf, cp);
133             preauth = TRUE;
134             return(PS_SUCCESS);
135         }
136         else if (strncmp(cp, "OK", 2) == 0)
137         {
138             if (argbuf)
139                 strcpy(argbuf, cp);
140             return(PS_SUCCESS);
141         }
142         else if (strncmp(cp, "BAD", 3) == 0)
143             return(PS_ERROR);
144         else if (strncmp(cp, "NO", 2) == 0)
145             return(PS_ERROR);
146         else
147             return(PS_PROTOCOL);
148     }
149 }
150
151 #if OPIE_ENABLE
152 static int do_otp(int sock, struct query *ctl)
153 {
154     int i, rval;
155     char buffer[128];
156     char challenge[OPIE_CHALLENGE_MAX+1];
157     char response[OPIE_RESPONSE_MAX+1];
158
159     gen_send(sock, "AUTHENTICATE X-OTP");
160
161     if (rval = gen_recv(sock, buffer, sizeof(buffer)))
162         return rval;
163
164     if ((i = from64tobits(challenge, buffer)) < 0) {
165         report(stderr, _("Could not decode initial BASE64 challenge\n"));
166         return PS_AUTHFAIL;
167     };
168
169
170     to64frombits(buffer, ctl->remotename, strlen(ctl->remotename));
171
172     if (outlevel >= O_MONITOR)
173         report(stdout, "IMAP> %s\n", buffer);
174
175     /* best not to count on the challenge code handling multiple writes */
176     strcat(buffer, "\r\n");
177     SockWrite(sock, buffer, strlen(buffer));
178
179     if (rval = gen_recv(sock, buffer, sizeof(buffer)))
180         return rval;
181
182     if ((i = from64tobits(challenge, buffer)) < 0) {
183         report(stderr, _("Could not decode OTP challenge\n"));
184         return PS_AUTHFAIL;
185     };
186
187     rval = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
188     if ((rval == -2) && !run.poll_interval) {
189         char secret[OPIE_SECRET_MAX+1];
190         fprintf(stderr, _("Secret pass phrase: "));
191         if (opiereadpass(secret, sizeof(secret), 0))
192             rval = opiegenerator(challenge, secret, response);
193         memset(secret, 0, sizeof(secret));
194     };
195
196     if (rval)
197         return PS_AUTHFAIL;
198
199     to64frombits(buffer, response, strlen(response));
200
201     if (outlevel >= O_MONITOR)
202         report(stdout, "IMAP> %s\n", buffer);
203     strcat(buffer, "\r\n");
204     SockWrite(sock, buffer, strlen(buffer));
205
206     if (rval = gen_recv(sock, buffer, sizeof(buffer)))
207         return rval;
208
209     if (strstr(buffer, "OK"))
210         return PS_SUCCESS;
211     else
212         return PS_AUTHFAIL;
213 };
214 #endif /* OPIE_ENABLE */
215
216 #ifdef KERBEROS_V4
217 #if SIZEOF_INT == 4
218 typedef int     int32;
219 #elif SIZEOF_SHORT == 4
220 typedef short   int32;
221 #elif SIZEOF_LONG == 4
222 typedef long    int32;
223 #else
224 #error Cannot deduce a 32-bit-type
225 #endif
226
227 static int do_rfc1731(int sock, char *truename)
228 /* authenticate as per RFC1731 -- note 32-bit integer requirement here */
229 {
230     int result = 0, len;
231     char buf1[4096], buf2[4096];
232     union {
233       int32 cint;
234       char cstr[4];
235     } challenge1, challenge2;
236     char srvinst[INST_SZ];
237     char *p;
238     char srvrealm[REALM_SZ];
239     KTEXT_ST authenticator;
240     CREDENTIALS credentials;
241     char tktuser[MAX_K_NAME_SZ+1+INST_SZ+1+REALM_SZ+1];
242     char tktinst[INST_SZ];
243     char tktrealm[REALM_SZ];
244     des_cblock session;
245     des_key_schedule schedule;
246
247     gen_send(sock, "AUTHENTICATE KERBEROS_V4");
248
249     /* The data encoded in the first ready response contains a random
250      * 32-bit number in network byte order.  The client should respond
251      * with a Kerberos ticket and an authenticator for the principal
252      * "imap.hostname@realm", where "hostname" is the first component
253      * of the host name of the server with all letters in lower case
254      * and where "realm" is the Kerberos realm of the server.  The
255      * encrypted checksum field included within the Kerberos
256      * authenticator should contain the server provided 32-bit number
257      * in network byte order.
258      */
259
260     if (result = gen_recv(sock, buf1, sizeof buf1)) {
261         return result;
262     }
263
264     len = from64tobits(challenge1.cstr, buf1);
265     if (len < 0) {
266         report(stderr, _("could not decode initial BASE64 challenge\n"));
267         return PS_AUTHFAIL;
268     }
269
270     /* this patch by Dan Root <dar@thekeep.org> solves an endianess
271      * problem. */
272     {
273         char tmp[4];
274
275         *(int *)tmp = ntohl(*(int *) challenge1.cstr);
276         memcpy(challenge1.cstr, tmp, sizeof(tmp));
277     }
278
279     /* Client responds with a Kerberos ticket and an authenticator for
280      * the principal "imap.hostname@realm" where "hostname" is the
281      * first component of the host name of the server with all letters
282      * in lower case and where "realm" is the Kerberos realm of the
283      * server.  The encrypted checksum field included within the
284      * Kerberos authenticator should contain the server-provided
285      * 32-bit number in network byte order.
286      */
287
288     strncpy(srvinst, truename, (sizeof srvinst)-1);
289     srvinst[(sizeof srvinst)-1] = '\0';
290     for (p = srvinst; *p; p++) {
291       if (isupper(*p)) {
292         *p = tolower(*p);
293       }
294     }
295
296     strncpy(srvrealm, (char *)krb_realmofhost(srvinst), (sizeof srvrealm)-1);
297     srvrealm[(sizeof srvrealm)-1] = '\0';
298     if (p = strchr(srvinst, '.')) {
299       *p = '\0';
300     }
301
302     result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm, 0);
303     if (result) {
304         report(stderr, "krb_mq_req: %s\n", krb_get_err_text(result));
305         return PS_AUTHFAIL;
306     }
307
308     result = krb_get_cred("imap", srvinst, srvrealm, &credentials);
309     if (result) {
310         report(stderr, "krb_get_cred: %s\n", krb_get_err_text(result));
311         return PS_AUTHFAIL;
312     }
313
314     memcpy(session, credentials.session, sizeof session);
315     memset(&credentials, 0, sizeof credentials);
316     des_key_sched(&session, schedule);
317
318     result = krb_get_tf_fullname(TKT_FILE, tktuser, tktinst, tktrealm);
319     if (result) {
320         report(stderr, "krb_get_tf_fullname: %s\n", krb_get_err_text(result));
321         return PS_AUTHFAIL;
322     }
323
324     if (strcmp(tktuser, user) != 0) {
325         report(stderr, 
326                _("principal %s in ticket does not match -u %s\n"), tktuser,
327                 user);
328         return PS_AUTHFAIL;
329     }
330
331     if (tktinst[0]) {
332         report(stderr, 
333                _("non-null instance (%s) might cause strange behavior\n"),
334                 tktinst);
335         strcat(tktuser, ".");
336         strcat(tktuser, tktinst);
337     }
338
339     if (strcmp(tktrealm, srvrealm) != 0) {
340         strcat(tktuser, "@");
341         strcat(tktuser, tktrealm);
342     }
343
344     result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm,
345             challenge1.cint);
346     if (result) {
347         report(stderr, "krb_mq_req: %s\n", krb_get_err_text(result));
348         return PS_AUTHFAIL;
349     }
350
351     to64frombits(buf1, authenticator.dat, authenticator.length);
352     if (outlevel >= O_MONITOR) {
353         report(stdout, "IMAP> %s\n", buf1);
354     }
355     strcat(buf1, "\r\n");
356     SockWrite(sock, buf1, strlen(buf1));
357
358     /* Upon decrypting and verifying the ticket and authenticator, the
359      * server should verify that the contained checksum field equals
360      * the original server provided random 32-bit number.  Should the
361      * verification be successful, the server must add one to the
362      * checksum and construct 8 octets of data, with the first four
363      * octets containing the incremented checksum in network byte
364      * order, the fifth octet containing a bit-mask specifying the
365      * protection mechanisms supported by the server, and the sixth
366      * through eighth octets containing, in network byte order, the
367      * maximum cipher-text buffer size the server is able to receive.
368      * The server must encrypt the 8 octets of data in the session key
369      * and issue that encrypted data in a second ready response.  The
370      * client should consider the server authenticated if the first
371      * four octets the un-encrypted data is equal to one plus the
372      * checksum it previously sent.
373      */
374     
375     if (result = gen_recv(sock, buf1, sizeof buf1))
376         return result;
377
378     /* The client must construct data with the first four octets
379      * containing the original server-issued checksum in network byte
380      * order, the fifth octet containing the bit-mask specifying the
381      * selected protection mechanism, the sixth through eighth octets
382      * containing in network byte order the maximum cipher-text buffer
383      * size the client is able to receive, and the following octets
384      * containing a user name string.  The client must then append
385      * from one to eight octets so that the length of the data is a
386      * multiple of eight octets. The client must then PCBC encrypt the
387      * data with the session key and respond to the second ready
388      * response with the encrypted data.  The server decrypts the data
389      * and verifies the contained checksum.  The username field
390      * identifies the user for whom subsequent IMAP operations are to
391      * be performed; the server must verify that the principal
392      * identified in the Kerberos ticket is authorized to connect as
393      * that user.  After these verifications, the authentication
394      * process is complete.
395      */
396
397     len = from64tobits(buf2, buf1);
398     if (len < 0) {
399         report(stderr, _("could not decode BASE64 ready response\n"));
400         return PS_AUTHFAIL;
401     }
402
403     des_ecb_encrypt((des_cblock *)buf2, (des_cblock *)buf2, schedule, 0);
404     memcpy(challenge2.cstr, buf2, 4);
405     if (ntohl(challenge2.cint) != challenge1.cint + 1) {
406         report(stderr, _("challenge mismatch\n"));
407         return PS_AUTHFAIL;
408     }       
409
410     memset(authenticator.dat, 0, sizeof authenticator.dat);
411
412     result = htonl(challenge1.cint);
413     memcpy(authenticator.dat, &result, sizeof result);
414
415     /* The protection mechanisms and their corresponding bit-masks are as
416      * follows:
417      *
418      * 1 No protection mechanism
419      * 2 Integrity (krb_mk_safe) protection
420      * 4 Privacy (krb_mk_priv) protection
421      */
422     authenticator.dat[4] = 1;
423
424     len = strlen(tktuser);
425     strncpy(authenticator.dat+8, tktuser, len);
426     authenticator.length = len + 8 + 1;
427     while (authenticator.length & 7) {
428         authenticator.length++;
429     }
430     des_pcbc_encrypt((des_cblock *)authenticator.dat,
431             (des_cblock *)authenticator.dat, authenticator.length, schedule,
432             &session, 1);
433
434     to64frombits(buf1, authenticator.dat, authenticator.length);
435     if (outlevel >= O_MONITOR) {
436         report(stdout, "IMAP> %s\n", buf1);
437     }
438
439     strcat(buf1, "\r\n");
440     SockWrite(sock, buf1, strlen(buf1));
441
442     if (result = gen_recv(sock, buf1, sizeof buf1))
443         return result;
444
445     if (strstr(buf1, "OK")) {
446         return PS_SUCCESS;
447     }
448     else {
449         return PS_AUTHFAIL;
450     }
451 }
452 #endif /* KERBEROS_V4 */
453
454 #ifdef GSSAPI
455 #define GSSAUTH_P_NONE      1
456 #define GSSAUTH_P_INTEGRITY 2
457 #define GSSAUTH_P_PRIVACY   4
458
459 static int do_gssauth(int sock, char *hostname, char *username)
460 {
461     gss_buffer_desc request_buf, send_token;
462     gss_buffer_t sec_token;
463     gss_name_t target_name;
464     gss_ctx_id_t context;
465     gss_OID mech_name;
466     gss_qop_t quality;
467     int cflags;
468     OM_uint32 maj_stat, min_stat;
469     char buf1[8192], buf2[8192], server_conf_flags;
470     unsigned long buf_size;
471     int result;
472
473     /* first things first: get an imap ticket for host */
474     sprintf(buf1, "imap@%s", hostname);
475     request_buf.value = buf1;
476     request_buf.length = strlen(buf1) + 1;
477     maj_stat = gss_import_name(&min_stat, &request_buf, GSS_C_NT_HOSTBASED_SERVICE,
478         &target_name);
479     if (maj_stat != GSS_S_COMPLETE) {
480         report(stderr, _("Couldn't get service name for [%s]\n"), buf1);
481         return PS_AUTHFAIL;
482     }
483     else if (outlevel >= O_DEBUG) {
484         maj_stat = gss_display_name(&min_stat, target_name, &request_buf,
485             &mech_name);
486         report(stderr, _("Using service name [%s]\n"),request_buf.value);
487         maj_stat = gss_release_buffer(&min_stat, &request_buf);
488     }
489
490     gen_send(sock, "AUTHENTICATE GSSAPI");
491
492     /* upon receipt of the GSSAPI authentication request, server returns
493      * null data ready response. */
494     if (result = gen_recv(sock, buf1, sizeof buf1)) {
495         return result;
496     }
497
498     /* now start the security context initialisation loop... */
499     sec_token = GSS_C_NO_BUFFER;
500     context = GSS_C_NO_CONTEXT;
501     if (outlevel >= O_VERBOSE)
502         report(stdout, _("Sending credentials\n"));
503     do {
504         send_token.length = 0;
505         send_token.value = NULL;
506         maj_stat = gss_init_sec_context(&min_stat, 
507                                         GSS_C_NO_CREDENTIAL,
508                                         &context, 
509                                         target_name, 
510                                         GSS_C_NO_OID, 
511                                         GSS_C_MUTUAL_FLAG | GSS_C_SEQUENCE_FLAG, 
512                                         0, 
513                                         GSS_C_NO_CHANNEL_BINDINGS, 
514                                         sec_token, 
515                                         NULL, 
516                                         &send_token, 
517                                         NULL, 
518                                         NULL);
519         if (maj_stat!=GSS_S_COMPLETE && maj_stat!=GSS_S_CONTINUE_NEEDED) {
520             report(stderr, _("Error exchanging credentials\n"));
521             gss_release_name(&min_stat, &target_name);
522             /* wake up server and await NO response */
523             SockWrite(sock, "\r\n", 2);
524             if (result = gen_recv(sock, buf1, sizeof buf1))
525                 return result;
526             return PS_AUTHFAIL;
527         }
528         to64frombits(buf1, send_token.value, send_token.length);
529         gss_release_buffer(&min_stat, &send_token);
530         strcat(buf1, "\r\n");
531         SockWrite(sock, buf1, strlen(buf1));
532         if (outlevel >= O_MONITOR)
533             report(stdout, "IMAP> %s\n", buf1);
534         if (maj_stat == GSS_S_CONTINUE_NEEDED) {
535             if (result = gen_recv(sock, buf1, sizeof buf1)) {
536                 gss_release_name(&min_stat, &target_name);
537                 return result;
538             }
539             request_buf.length = from64tobits(buf2, buf1 + 2);
540             request_buf.value = buf2;
541             sec_token = &request_buf;
542         }
543     } while (maj_stat == GSS_S_CONTINUE_NEEDED);
544     gss_release_name(&min_stat, &target_name);
545
546     /* get security flags and buffer size */
547     if (result = gen_recv(sock, buf1, sizeof buf1)) {
548         return result;
549     }
550     request_buf.length = from64tobits(buf2, buf1 + 2);
551     request_buf.value = buf2;
552
553     maj_stat = gss_unwrap(&min_stat, context, &request_buf, &send_token,
554         &cflags, &quality);
555     if (maj_stat != GSS_S_COMPLETE) {
556         report(stderr, _("Couldn't unwrap security level data\n"));
557         gss_release_buffer(&min_stat, &send_token);
558         return PS_AUTHFAIL;
559     }
560     if (outlevel >= O_DEBUG)
561         report(stdout, _("Credential exchange complete\n"));
562     /* first octet is security levels supported. We want none, for now */
563     server_conf_flags = ((char *)send_token.value)[0];
564     if ( !(((char *)send_token.value)[0] & GSSAUTH_P_NONE) ) {
565         report(stderr, _("Server requires integrity and/or privacy\n"));
566         gss_release_buffer(&min_stat, &send_token);
567         return PS_AUTHFAIL;
568     }
569     ((char *)send_token.value)[0] = 0;
570     buf_size = ntohl(*((long *)send_token.value));
571     /* we don't care about buffer size if we don't wrap data */
572     gss_release_buffer(&min_stat, &send_token);
573     if (outlevel >= O_DEBUG) {
574         report(stdout, _("Unwrapped security level flags: %s%s%s\n"),
575             server_conf_flags & GSSAUTH_P_NONE ? "N" : "-",
576             server_conf_flags & GSSAUTH_P_INTEGRITY ? "I" : "-",
577             server_conf_flags & GSSAUTH_P_PRIVACY ? "C" : "-");
578         report(stdout, _("Maximum GSS token size is %ld\n"),buf_size);
579     }
580
581     /* now respond in kind (hack!!!) */
582     buf_size = htonl(buf_size); /* do as they do... only matters if we do enc */
583     memcpy(buf1, &buf_size, 4);
584     buf1[0] = GSSAUTH_P_NONE;
585     strcpy(buf1+4, username); /* server decides if princ is user */
586     request_buf.length = 4 + strlen(username) + 1;
587     request_buf.value = buf1;
588     maj_stat = gss_wrap(&min_stat, context, 0, GSS_C_QOP_DEFAULT, &request_buf,
589         &cflags, &send_token);
590     if (maj_stat != GSS_S_COMPLETE) {
591         report(stderr, _("Error creating security level request\n"));
592         return PS_AUTHFAIL;
593     }
594     to64frombits(buf1, send_token.value, send_token.length);
595     if (outlevel >= O_DEBUG) {
596         report(stdout, _("Requesting authorisation as %s\n"), username);
597         report(stdout, "IMAP> %s\n",buf1);
598     }
599     strcat(buf1, "\r\n");
600     SockWrite(sock, buf1, strlen(buf1));
601
602     /* we should be done. Get status and finish up */
603     if (result = gen_recv(sock, buf1, sizeof buf1))
604         return result;
605     if (strstr(buf1, "OK")) {
606         /* flush security context */
607         if (outlevel >= O_DEBUG)
608             report(stdout, _("Releasing GSS credentials\n"));
609         maj_stat = gss_delete_sec_context(&min_stat, &context, &send_token);
610         if (maj_stat != GSS_S_COMPLETE) {
611             report(stderr, _("Error releasing credentials\n"));
612             return PS_AUTHFAIL;
613         }
614         /* send_token may contain a notification to the server to flush
615          * credentials. RFC 1731 doesn't specify what to do, and since this
616          * support is only for authentication, we'll assume the server
617          * knows enough to flush its own credentials */
618         gss_release_buffer(&min_stat, &send_token);
619         return PS_SUCCESS;
620     }
621
622     return PS_AUTHFAIL;
623 }       
624 #endif /* GSSAPI */
625
626 static void hmac_md5 (unsigned char *password,  size_t pass_len,
627                       unsigned char *challenge, size_t chal_len,
628                       unsigned char *response,  size_t resp_len)
629 {
630     int i;
631     unsigned char ipad[64];
632     unsigned char opad[64];
633     unsigned char hash_passwd[16];
634
635     MD5_CTX ctx;
636     
637     if (resp_len != 16)
638         return;
639
640     if (pass_len > sizeof (ipad))
641     {
642         MD5Init (&ctx);
643         MD5Update (&ctx, password, pass_len);
644         MD5Final (hash_passwd, &ctx);
645         password = hash_passwd; pass_len = sizeof (hash_passwd);
646     }
647
648     memset (ipad, 0, sizeof (ipad));
649     memset (opad, 0, sizeof (opad));
650     memcpy (ipad, password, pass_len);
651     memcpy (opad, password, pass_len);
652
653     for (i=0; i<64; i++) {
654         ipad[i] ^= 0x36;
655         opad[i] ^= 0x5c;
656     }
657
658     MD5Init (&ctx);
659     MD5Update (&ctx, ipad, sizeof (ipad));
660     MD5Update (&ctx, challenge, chal_len);
661     MD5Final (response, &ctx);
662
663     MD5Init (&ctx);
664     MD5Update (&ctx, opad, sizeof (opad));
665     MD5Update (&ctx, response, resp_len);
666     MD5Final (response, &ctx);
667 }
668
669 #if NTLM_ENABLE
670 #include "ntlm.h"
671
672 static tSmbNtlmAuthRequest   request;              
673 static tSmbNtlmAuthChallenge challenge;
674 static tSmbNtlmAuthResponse  response;
675
676 /*
677  * NTLM support by Grant Edwards.
678  *
679  * Handle MS-Exchange NTLM authentication method.  This is the same
680  * as the NTLM auth used by Samba for SMB related services. We just
681  * encode the packets in base64 instead of sending them out via a
682  * network interface.
683  * 
684  * Much source (ntlm.h, smb*.c smb*.h) was borrowed from Samba.
685  */
686
687 static int do_imap_ntlm(int sock, struct query *ctl)
688 {
689     char msgbuf[2048];
690     int result,len;
691   
692     gen_send(sock, "AUTHENTICATE NTLM");
693
694     if ((result = gen_recv(sock, msgbuf, sizeof msgbuf)))
695         return result;
696   
697     if (msgbuf[0] != '+')
698         return PS_AUTHFAIL;
699   
700     buildSmbNtlmAuthRequest(&request,ctl->remotename,NULL);
701
702     if (outlevel >= O_DEBUG)
703         dumpSmbNtlmAuthRequest(stdout, &request);
704
705     memset(msgbuf,0,sizeof msgbuf);
706     to64frombits (msgbuf, (unsigned char*)&request, SmbLength(&request));
707   
708     if (outlevel >= O_MONITOR)
709         report(stdout, "IMAP> %s\n", msgbuf);
710   
711     strcat(msgbuf,"\r\n");
712     SockWrite (sock, msgbuf, strlen (msgbuf));
713
714     if ((gen_recv(sock, msgbuf, sizeof msgbuf)))
715         return result;
716   
717     len = from64tobits ((unsigned char*)&challenge, msgbuf);
718     
719     if (outlevel >= O_DEBUG)
720         dumpSmbNtlmAuthChallenge(stdout, &challenge);
721     
722     buildSmbNtlmAuthResponse(&challenge, &response,ctl->remotename,ctl->password);
723   
724     if (outlevel >= O_DEBUG)
725         dumpSmbNtlmAuthResponse(stdout, &response);
726   
727     memset(msgbuf,0,sizeof msgbuf);
728     to64frombits (msgbuf, (unsigned char*)&response, SmbLength(&response));
729
730     if (outlevel >= O_MONITOR)
731         report(stdout, "IMAP> %s\n", msgbuf);
732       
733     strcat(msgbuf,"\r\n");
734
735     SockWrite (sock, msgbuf, strlen (msgbuf));
736   
737     if ((result = gen_recv (sock, msgbuf, sizeof msgbuf)))
738         return result;
739   
740     if (strstr (msgbuf, "OK"))
741         return PS_SUCCESS;
742     else
743         return PS_AUTHFAIL;
744 }
745 #endif /* NTLM */
746
747 static int do_cram_md5 (int sock, struct query *ctl)
748 /* authenticate as per RFC2195 */
749 {
750     int result;
751     int len;
752     unsigned char buf1[1024];
753     unsigned char msg_id[768];
754     unsigned char response[16];
755     unsigned char reply[1024];
756
757     gen_send (sock, "AUTHENTICATE CRAM-MD5");
758
759     /* From RFC2195:
760      * The data encoded in the first ready response contains an
761      * presumptively arbitrary string of random digits, a timestamp, and the
762      * fully-qualified primary host name of the server.  The syntax of the
763      * unencoded form must correspond to that of an RFC 822 'msg-id'
764      * [RFC822] as described in [POP3].
765      */
766
767     if ((result = gen_recv (sock, buf1, sizeof (buf1)))) {
768         return result;
769     }
770
771     len = from64tobits (msg_id, buf1);
772     if (len < 0) {
773         report (stderr, _("could not decode BASE64 challenge\n"));
774         return PS_AUTHFAIL;
775     } else if (len < sizeof (msg_id)) {
776         msg_id[len] = 0;
777     } else {
778         msg_id[sizeof (msg_id)-1] = 0;
779     }
780     if (outlevel >= O_DEBUG) {
781         report (stdout, "decoded as %s\n", msg_id);
782     }
783
784     /* The client makes note of the data and then responds with a string
785      * consisting of the user name, a space, and a 'digest'.  The latter is
786      * computed by applying the keyed MD5 algorithm from [KEYED-MD5] where
787      * the key is a shared secret and the digested text is the timestamp
788      * (including angle-brackets).
789      */
790
791     hmac_md5 (ctl->password, strlen (ctl->password),
792               msg_id, strlen (msg_id),
793               response, sizeof (response));
794
795 #ifdef HAVE_SNPRINTF
796     snprintf (reply, sizeof (reply),
797 #else
798     sprintf(reply,
799 #endif
800               "%s %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", 
801               ctl->remotename,
802               response[0], response[1], response[2], response[3],
803               response[4], response[5], response[6], response[7],
804               response[8], response[9], response[10], response[11],
805               response[12], response[13], response[14], response[15]);
806
807     if (outlevel >= O_DEBUG) {
808         report (stdout, "replying with %s\n", reply);
809     }
810
811     to64frombits (buf1, reply, strlen (reply));
812     if (outlevel >= O_MONITOR) {
813         report (stdout, "IMAP> %s\n", buf1);
814     }
815
816     /* PMDF5.2 IMAP has a bug that requires this to be a single write */
817     strcat (buf1, "\r\n");
818     SockWrite (sock, buf1, strlen (buf1));
819
820     if ((result = gen_recv (sock, buf1, sizeof (buf1))))
821         return result;
822
823     if (strstr (buf1, "OK")) {
824         return PS_SUCCESS;
825     } else {
826         return PS_AUTHFAIL;
827     }
828 }
829
830 int imap_canonicalize(char *result, char *raw, int maxlen)
831 /* encode an IMAP password as per RFC1730's quoting conventions */
832 {
833     int i, j;
834
835     j = 0;
836     for (i = 0; i < strlen(raw) && i < maxlen; i++)
837     {
838         if ((raw[i] == '\\') || (raw[i] == '"'))
839             result[j++] = '\\';
840         result[j++] = raw[i];
841     }
842     result[j] = '\0';
843
844     return(i);
845 }
846
847 int imap_getauth(int sock, struct query *ctl, char *greeting)
848 /* apply for connection authorization */
849 {
850     int ok = 0;
851
852     /* probe to see if we're running IMAP4 and can use RFC822.PEEK */
853     capabilities[0] = '\0';
854     if ((ok = gen_transact(sock, "CAPABILITY")) == PS_SUCCESS)
855     {
856         /* UW-IMAP server 10.173 notifies in all caps */
857         if (strstr(capabilities, "IMAP4REV1"))
858         {
859             imap_version = IMAP4rev1;
860             if (outlevel >= O_DEBUG)
861                 report(stdout, _("Protocol identified as IMAP4 rev 1\n"));
862         }
863         else
864         {
865             imap_version = IMAP4;
866             if (outlevel >= O_DEBUG)
867                 report(stdout, _("Protocol identified as IMAP4 rev 0\n"));
868         }
869     }
870     else if (ok == PS_ERROR)
871     {
872         imap_version = IMAP2;
873         if (outlevel >= O_DEBUG)
874             report(stdout, _("Protocol identified as IMAP2 or IMAP2BIS\n"));
875     }
876     else
877         return(ok);
878
879     peek_capable = (imap_version >= IMAP4);
880
881     /* 
882      * Assumption: expunges are cheap, so we want to do them
883      * after every message unless user said otherwise.
884      */
885     if (NUM_SPECIFIED(ctl->expunge))
886         expunge_period = NUM_VALUE_OUT(ctl->expunge);
887     else
888         expunge_period = 1;
889
890     if (preauth)
891         return(PS_SUCCESS);
892
893 #if OPIE_ENABLE
894     if ((ctl->server.protocol == P_IMAP) && strstr(capabilities, "AUTH=X-OTP"))
895     {
896         if (outlevel >= O_DEBUG)
897             report(stdout, _("OTP authentication is supported\n"));
898         if (do_otp(sock, ctl) == PS_SUCCESS)
899             return(PS_SUCCESS);
900     };
901 #endif /* OPIE_ENABLE */
902
903 #ifdef GSSAPI
904     if (strstr(capabilities, "AUTH=GSSAPI"))
905     {
906         if (ctl->server.protocol == P_IMAP_GSS)
907         {
908             if (outlevel >= O_DEBUG)
909                 report(stdout, _("GSS authentication is supported\n"));
910             return do_gssauth(sock, ctl->server.truename, ctl->remotename);
911         }
912     }
913     else if (ctl->server.protocol == P_IMAP_GSS)
914     {
915         report(stderr, 
916                _("Required GSS capability not supported by server\n"));
917         return(PS_AUTHFAIL);
918     }
919 #endif /* GSSAPI */
920
921 #ifdef KERBEROS_V4
922     if (strstr(capabilities, "AUTH=KERBEROS_V4"))
923     {
924         if (outlevel >= O_DEBUG)
925             report(stdout, _("KERBEROS_V4 authentication is supported\n"));
926
927         if (ctl->server.protocol == P_IMAP_K4)
928         {
929             if ((ok = do_rfc1731(sock, ctl->server.truename)))
930             {
931                 if (outlevel >= O_MONITOR)
932                     report(stdout, "IMAP> *\n");
933                 SockWrite(sock, "*\r\n", 3);
934             }
935             
936             return(ok);
937         }
938         /* else fall through to ordinary AUTH=LOGIN case */
939     }
940     else if (ctl->server.protocol == P_IMAP_K4)
941     {
942         report(stderr, 
943                _("Required KERBEROS_V4 capability not supported by server\n"));
944         return(PS_AUTHFAIL);
945     }
946 #endif /* KERBEROS_V4 */
947
948     if (strstr(capabilities, "AUTH=CRAM-MD5"))
949     {
950         if (outlevel >= O_DEBUG)
951             report (stdout, _("CRAM-MD5 authentication is supported\n"));
952         if (ctl->server.protocol != P_IMAP_LOGIN)
953         {
954             if ((ok = do_cram_md5 (sock, ctl)))
955             {
956                 if (outlevel >= O_MONITOR)
957                     report (stdout, "IMAP> *\n");
958                 SockWrite (sock, "*\r\n", 3);
959             }
960             return ok;
961         }
962     }
963     else if (ctl->server.protocol == P_IMAP_CRAM_MD5)
964     {
965         report(stderr,
966                _("Required CRAM-MD5 capability not supported by server\n"));
967         return(PS_AUTHFAIL);
968     }
969
970 #ifdef NTLM_ENABLE
971     if (strstr (capabilities, "AUTH=NTLM"))
972     {
973         if (outlevel >= O_DEBUG)
974             report (stdout, _("NTLM authentication is supported\n"));
975         return do_imap_ntlm (sock, ctl);
976     }
977 #endif /* NTLM_ENABLE */
978
979 #ifdef __UNUSED__       /* The Cyrus IMAP4rev1 server chokes on this */
980     /* this handles either AUTH=LOGIN or AUTH-LOGIN */
981     if ((imap_version >= IMAP4rev1) && (!strstr(capabilities, "LOGIN"))) {
982       report(stderr, 
983              _("Required LOGIN capability not supported by server\n"));
984       return PS_AUTHFAIL;
985     };
986 #endif /* __UNUSED__ */
987
988     {
989         /* these sizes guarantee no buffer overflow */
990         char    remotename[NAMELEN*2+1], password[PASSWORDLEN*2+1];
991
992         imap_canonicalize(remotename, ctl->remotename, NAMELEN);
993         imap_canonicalize(password, ctl->password, PASSWORDLEN);
994         ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", remotename, password);
995     }
996
997     if (ok)
998         return(ok);
999     
1000     return(PS_SUCCESS);
1001 }
1002
1003 static int internal_expunge(int sock)
1004 /* ship an expunge, resetting associated counters */
1005 {
1006     int ok;
1007
1008     if ((ok = gen_transact(sock, "EXPUNGE")))
1009         return(ok);
1010
1011     expunged += deletions;
1012     deletions = 0;
1013
1014 #ifdef IMAP_UID /* not used */
1015     expunge_uids(ctl);
1016 #endif /* IMAP_UID */
1017
1018     return(PS_SUCCESS);
1019 }
1020
1021 static int imap_getrange(int sock, 
1022                          struct query *ctl, 
1023                          const char *folder, 
1024                          int *countp, int *newp, int *bytes)
1025 /* get range of messages to be fetched */
1026 {
1027     int ok;
1028
1029     /* find out how many messages are waiting */
1030     *bytes = recent = unseen = -1;
1031
1032     if (pass > 1)
1033     {
1034         /* 
1035          * We have to have an expunge here, otherwise the re-poll will
1036          * infinite-loop picking up un-expunged messages -- unless the
1037          * expunge period is one and we've been nuking each message 
1038          * just after deletion.
1039          */
1040         ok = 0;
1041         if (deletions && expunge_period != 1)
1042             internal_expunge(sock);
1043         count = -1;
1044         if (ok || gen_transact(sock, "NOOP"))
1045         {
1046             report(stderr, _("re-poll failed\n"));
1047             return(ok);
1048         }
1049         else if (count == -1)   /* no EXISTS response to NOOP */
1050         {
1051             count = recent = 0;
1052             unseen = -1;
1053         }
1054     }
1055     else
1056     {
1057         if (!check_only)
1058             ok = gen_transact(sock, "SELECT %s", folder ? folder : "INBOX");
1059         else
1060             ok = gen_transact(sock, "EXAMINE %s", folder ? folder : "INBOX");
1061         if (ok != 0)
1062         {
1063             report(stderr, _("mailbox selection failed\n"));
1064             return(ok);
1065         }
1066     }
1067
1068     *countp = count;
1069
1070     /*
1071      * Note: because IMAP has an is_old method, this number is used
1072      * only for the "X messages (Y unseen)" notification.  Accordingly
1073      * it doesn't matter much that it can be wrong (e.g. if we see an
1074      * UNSEEN response but not all messages above the first UNSEEN one
1075      * are likewise).
1076      */
1077     if (unseen >= 0)            /* optional, but better if we see it */
1078         *newp = count - unseen + 1;
1079     else if (recent >= 0)       /* mandatory */
1080         *newp = recent;
1081     else
1082         *newp = -1;             /* should never happen, RECENT is mandatory */ 
1083
1084     expunged = 0;
1085
1086     return(PS_SUCCESS);
1087 }
1088
1089 static int imap_getsizes(int sock, int count, int *sizes)
1090 /* capture the sizes of all messages */
1091 {
1092     char buf [MSGBUFSIZE+1];
1093
1094     /*
1095      * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
1096      * won't accept 1:1 as valid set syntax.  Some implementors
1097      * should be taken out and shot for excessive anality.
1098      */
1099     if (count == 1)
1100         gen_send(sock, "FETCH 1 RFC822.SIZE", count);
1101     else
1102         gen_send(sock, "FETCH 1:%d RFC822.SIZE", count);
1103     for (;;)
1104     {
1105         int num, size, ok;
1106
1107         if ((ok = gen_recv(sock, buf, sizeof(buf))))
1108             return(ok);
1109         if (strstr(buf, "OK"))
1110             break;
1111         else if (sscanf(buf, "* %d FETCH (RFC822.SIZE %d)", &num, &size) == 2)
1112             sizes[num - 1] = size;
1113     }
1114
1115     return(PS_SUCCESS);
1116 }
1117
1118 static int imap_is_old(int sock, struct query *ctl, int number)
1119 /* is the given message old? */
1120 {
1121     int ok;
1122
1123     /* expunges change the fetch numbers */
1124     number -= expunged;
1125
1126     if ((ok = gen_transact(sock, "FETCH %d FLAGS", number)) != 0)
1127         return(PS_ERROR);
1128
1129     return(seen);
1130 }
1131
1132 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1133 /* request headers of nth message */
1134 {
1135     char buf [MSGBUFSIZE+1];
1136     int num;
1137
1138     /* expunges change the fetch numbers */
1139     number -= expunged;
1140
1141     /*
1142      * This is blessed by RFC1176, RFC1730, RFC2060.
1143      * According to the RFCs, it should *not* set the \Seen flag.
1144      */
1145     gen_send(sock, "FETCH %d RFC822.HEADER", number);
1146
1147     /* looking for FETCH response */
1148     do {
1149         int     ok;
1150
1151         if ((ok = gen_recv(sock, buf, sizeof(buf))))
1152             return(ok);
1153     } while
1154         (sscanf(buf+2, "%d FETCH (%*s {%d}", &num, lenp) != 2);
1155
1156     if (num != number)
1157         return(PS_ERROR);
1158     else
1159         return(PS_SUCCESS);
1160 }
1161
1162 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
1163 /* request body of nth message */
1164 {
1165     char buf [MSGBUFSIZE+1], *cp;
1166     int num;
1167
1168     /* expunges change the fetch numbers */
1169     number -= expunged;
1170
1171     /*
1172      * If we're using IMAP4, we can fetch the message without setting its
1173      * seen flag.  This is good!  It means that if the protocol exchange
1174      * craps out during the message, it will still be marked `unseen' on
1175      * the server.
1176      *
1177      * However...*don't* do this if we're using keep to suppress deletion!
1178      * In that case, marking the seen flag is the only way to prevent the
1179      * message from being re-fetched on subsequent runs (and according
1180      * to RFC2060 p.43 this fetch should set Seen as a side effect).
1181      */
1182     switch (imap_version)
1183     {
1184     case IMAP4rev1:     /* RFC 2060 */
1185         if (!ctl->keep)
1186             gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
1187         else
1188             gen_send(sock, "FETCH %d BODY[TEXT]", number);
1189         break;
1190
1191     case IMAP4:         /* RFC 1730 */
1192         if (!ctl->keep)
1193             gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
1194         else
1195             gen_send(sock, "FETCH %d RFC822.TEXT", number);
1196         break;
1197
1198     default:            /* RFC 1176 */
1199         gen_send(sock, "FETCH %d RFC822.TEXT", number);
1200         break;
1201     }
1202
1203     /* looking for FETCH response */
1204     do {
1205         int     ok;
1206
1207         if ((ok = gen_recv(sock, buf, sizeof(buf))))
1208             return(ok);
1209     } while
1210         (!strstr(buf+4, "FETCH") || sscanf(buf+2, "%d", &num) != 1);
1211
1212     if (num != number)
1213         return(PS_ERROR);
1214
1215     /*
1216      * Try to extract a length from the FETCH response.  RFC2060 requires
1217      * it to be present, but at least one IMAP server (Novell GroupWise)
1218      * botches this.
1219      */
1220     if ((cp = strchr(buf, '{')))
1221         *lenp = atoi(cp + 1);
1222     else
1223         *lenp = -1;     /* missing length part in FETCH reponse */
1224
1225     return(PS_SUCCESS);
1226 }
1227
1228 static int imap_trail(int sock, struct query *ctl, int number)
1229 /* discard tail of FETCH response after reading message text */
1230 {
1231     /* expunges change the fetch numbers */
1232     /* number -= expunged; */
1233
1234     for (;;)
1235     {
1236         char buf[MSGBUFSIZE+1];
1237         int ok;
1238
1239         if ((ok = gen_recv(sock, buf, sizeof(buf))))
1240             return(ok);
1241
1242         /* UW IMAP returns "OK FETCH", Cyrus returns "OK Completed" */
1243         if (strstr(buf, "OK"))
1244             break;
1245
1246 #ifdef __UNUSED__
1247         /*
1248          * Any IMAP server that fails to set Seen on a BODY[TEXT]
1249          * fetch violates RFC2060 p.43 (top).  This becomes an issue
1250          * when keep is on, because seen messages aren't deleted and
1251          * get refetched on each poll.  As a workaround, if keep is on
1252          * we can set the Seen flag explicitly.
1253          *
1254          * This code isn't used yet because we don't know of any IMAP
1255          * servers broken in this way.
1256          */
1257         if (ctl->keep)
1258             if ((ok = gen_transact(sock,
1259                         imap_version == IMAP4 
1260                                 ? "STORE %d +FLAGS.SILENT (\\Seen)"
1261                                 : "STORE %d +FLAGS (\\Seen)", 
1262                         number)))
1263                 return(ok);
1264 #endif /* __UNUSED__ */
1265     }
1266
1267     return(PS_SUCCESS);
1268 }
1269
1270 static int imap_delete(int sock, struct query *ctl, int number)
1271 /* set delete flag for given message */
1272 {
1273     int ok;
1274
1275     /* expunges change the fetch numbers */
1276     number -= expunged;
1277
1278     /*
1279      * Use SILENT if possible as a minor throughput optimization.
1280      * Note: this has been dropped from IMAP4rev1.
1281      *
1282      * We set Seen because there are some IMAP servers (notably HP
1283      * OpenMail) that do message-receipt DSNs, but only when the seen
1284      * bit is set.  This is the appropriate time -- we get here right
1285      * after the local SMTP response that says delivery was
1286      * successful.
1287      */
1288     if ((ok = gen_transact(sock,
1289                         imap_version == IMAP4 
1290                                 ? "STORE %d +FLAGS.SILENT (\\Seen \\Deleted)"
1291                                 : "STORE %d +FLAGS (\\Seen \\Deleted)", 
1292                         number)))
1293         return(ok);
1294     else
1295         deletions++;
1296
1297     /*
1298      * We do an expunge after expunge_period messages, rather than
1299      * just before quit, so that a line hit during a long session
1300      * won't result in lots of messages being fetched again during
1301      * the next session.
1302      */
1303     if (NUM_NONZERO(expunge_period) && (deletions % expunge_period) == 0)
1304         internal_expunge(sock);
1305
1306     return(PS_SUCCESS);
1307 }
1308
1309 static int imap_logout(int sock, struct query *ctl)
1310 /* send logout command */
1311 {
1312     /* if any un-expunged deletions remain, ship an expunge now */
1313     if (deletions)
1314         internal_expunge(sock);
1315
1316     return(gen_transact(sock, "LOGOUT"));
1317 }
1318
1319 const static struct method imap =
1320 {
1321     "IMAP",             /* Internet Message Access Protocol */
1322 #if INET6_ENABLE
1323     "imap",
1324     "imaps",
1325 #else /* INET6_ENABLE */
1326     143,                /* standard IMAP2bis/IMAP4 port */
1327     993,                /* ssl IMAP2bis/IMAP4 port */
1328 #endif /* INET6_ENABLE */
1329     TRUE,               /* this is a tagged protocol */
1330     FALSE,              /* no message delimiter */
1331     imap_ok,            /* parse command response */
1332     imap_canonicalize,  /* deal with embedded slashes and spaces */
1333     imap_getauth,       /* get authorization */
1334     imap_getrange,      /* query range of messages */
1335     imap_getsizes,      /* get sizes of messages (used for ESMTP SIZE option) */
1336     imap_is_old,        /* no UID check */
1337     imap_fetch_headers, /* request given message headers */
1338     imap_fetch_body,    /* request given message body */
1339     imap_trail,         /* eat message trailer */
1340     imap_delete,        /* delete the message */
1341     imap_logout,        /* expunge and exit */
1342     TRUE,               /* yes, we can re-poll */
1343 };
1344
1345 int doIMAP(struct query *ctl)
1346 /* retrieve messages using IMAP Version 2bis or Version 4 */
1347 {
1348     return(do_protocol(ctl, &imap));
1349 }
1350
1351 /* imap.c ends here */