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