]> Pileus Git - ~andy/fetchmail/blobdiff - imap.c
LinuxWorld hacks.
[~andy/fetchmail] / imap.c
diff --git a/imap.c b/imap.c
index c84af17d9ca9fa983a68912de3510c9f97245460..3e39b6fb050b7490254c28488ad06a513d644f59 100644 (file)
--- a/imap.c
+++ b/imap.c
@@ -49,9 +49,9 @@
 
 #include "md5.h"
 
-#if OPIE
+#if OPIE_ENABLE
 #include <opie.h>
-#endif /* OPIE */
+#endif /* OPIE_ENABLE */
 
 #ifndef strstr         /* glibc-2.1 declares this as a macro */
 extern char *strstr(); /* needed on sysV68 R3V7.1. */
@@ -107,6 +107,8 @@ int imap_ok(int sock, char *argbuf)
        }
        if (strstr(buf, "FLAGS"))
            seen = (strstr(buf, "SEEN") != (char *)NULL);
+       if (strstr(buf, "PREAUTH"))
+           preauth = TRUE;
     } while
        (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
 
@@ -142,13 +144,18 @@ int imap_ok(int sock, char *argbuf)
        else if (strncmp(cp, "BAD", 3) == 0)
            return(PS_ERROR);
        else if (strncmp(cp, "NO", 2) == 0)
-           return(PS_ERROR);
+       {
+           if (stage == STAGE_GETAUTH) 
+               return(PS_AUTHFAIL);    /* RFC2060, 6.2.2 */
+           else
+               return(PS_ERROR);
+       }
        else
            return(PS_PROTOCOL);
     }
 }
 
-#if OPIE
+#if OPIE_ENABLE
 static int do_otp(int sock, struct query *ctl)
 {
     int i, rval;
@@ -171,8 +178,10 @@ static int do_otp(int sock, struct query *ctl)
 
     if (outlevel >= O_MONITOR)
        report(stdout, "IMAP> %s\n", buffer);
+
+    /* best not to count on the challenge code handling multiple writes */
+    strcat(buffer, "\r\n");
     SockWrite(sock, buffer, strlen(buffer));
-    SockWrite(sock, "\r\n", 2);
 
     if (rval = gen_recv(sock, buffer, sizeof(buffer)))
        return rval;
@@ -192,14 +201,14 @@ static int do_otp(int sock, struct query *ctl)
     };
 
     if (rval)
-       return PS_AUTHFAIL;
+       return(PS_AUTHFAIL);
 
     to64frombits(buffer, response, strlen(response));
 
     if (outlevel >= O_MONITOR)
        report(stdout, "IMAP> %s\n", buffer);
+    strcat(buffer, "\r\n");
     SockWrite(sock, buffer, strlen(buffer));
-    SockWrite(sock, "\r\n", 2);
 
     if (rval = gen_recv(sock, buffer, sizeof(buffer)))
        return rval;
@@ -209,7 +218,7 @@ static int do_otp(int sock, struct query *ctl)
     else
        return PS_AUTHFAIL;
 };
-#endif /* OPIE */
+#endif /* OPIE_ENABLE */
 
 #ifdef KERBEROS_V4
 #if SIZEOF_INT == 4
@@ -259,7 +268,14 @@ static int do_rfc1731(int sock, char *truename)
        return result;
     }
 
-    /* this patch by Dan Root <dar@thekeep.org> solves an endianess problem. */
+    len = from64tobits(challenge1.cstr, buf1);
+    if (len < 0) {
+       report(stderr, _("could not decode initial BASE64 challenge\n"));
+       return PS_AUTHFAIL;
+    }
+
+    /* this patch by Dan Root <dar@thekeep.org> solves an endianess
+     * problem. */
     {
        char tmp[4];
 
@@ -267,12 +283,6 @@ static int do_rfc1731(int sock, char *truename)
        memcpy(challenge1.cstr, tmp, sizeof(tmp));
     }
 
-    len = from64tobits(challenge1.cstr, buf1);
-    if (len < 0) {
-       report(stderr, _("could not decode initial BASE64 challenge\n"));
-       return PS_AUTHFAIL;
-    }
-
     /* Client responds with a Kerberos ticket and an authenticator for
      * the principal "imap.hostname@realm" where "hostname" is the
      * first component of the host name of the server with all letters
@@ -349,8 +359,8 @@ static int do_rfc1731(int sock, char *truename)
     if (outlevel >= O_MONITOR) {
        report(stdout, "IMAP> %s\n", buf1);
     }
+    strcat(buf1, "\r\n");
     SockWrite(sock, buf1, strlen(buf1));
-    SockWrite(sock, "\r\n", 2);
 
     /* Upon decrypting and verifying the ticket and authenticator, the
      * server should verify that the contained checksum field equals
@@ -432,8 +442,9 @@ static int do_rfc1731(int sock, char *truename)
     if (outlevel >= O_MONITOR) {
        report(stdout, "IMAP> %s\n", buf1);
     }
+
+    strcat(buf1, "\r\n");
     SockWrite(sock, buf1, strlen(buf1));
-    SockWrite(sock, "\r\n", 2);
 
     if (result = gen_recv(sock, buf1, sizeof buf1))
        return result;
@@ -523,8 +534,8 @@ static int do_gssauth(int sock, char *hostname, char *username)
         }
         to64frombits(buf1, send_token.value, send_token.length);
         gss_release_buffer(&min_stat, &send_token);
+       strcat(buf1, "\r\n");
         SockWrite(sock, buf1, strlen(buf1));
-        SockWrite(sock, "\r\n", 2);
         if (outlevel >= O_MONITOR)
             report(stdout, "IMAP> %s\n", buf1);
         if (maj_stat == GSS_S_CONTINUE_NEEDED) {
@@ -589,11 +600,11 @@ static int do_gssauth(int sock, char *hostname, char *username)
     }
     to64frombits(buf1, send_token.value, send_token.length);
     if (outlevel >= O_DEBUG) {
-        report(stdout, _("Requesting authorisation as %s\n"), username);
+        report(stdout, _("Requesting authorization as %s\n"), username);
         report(stdout, "IMAP> %s\n",buf1);
     }
+    strcat(buf1, "\r\n");
     SockWrite(sock, buf1, strlen(buf1));
-    SockWrite(sock, "\r\n", 2);
 
     /* we should be done. Get status and finish up */
     if (result = gen_recv(sock, buf1, sizeof buf1))
@@ -662,6 +673,83 @@ static void hmac_md5 (unsigned char *password,  size_t pass_len,
     MD5Final (response, &ctx);
 }
 
+#if NTLM_ENABLE
+#include "ntlm.h"
+
+static tSmbNtlmAuthRequest   request;             
+static tSmbNtlmAuthChallenge challenge;
+static tSmbNtlmAuthResponse  response;
+
+/*
+ * NTLM support by Grant Edwards.
+ *
+ * Handle MS-Exchange NTLM authentication method.  This is the same
+ * as the NTLM auth used by Samba for SMB related services. We just
+ * encode the packets in base64 instead of sending them out via a
+ * network interface.
+ * 
+ * Much source (ntlm.h, smb*.c smb*.h) was borrowed from Samba.
+ */
+
+static int do_imap_ntlm(int sock, struct query *ctl)
+{
+    char msgbuf[2048];
+    int result,len;
+  
+    gen_send(sock, "AUTHENTICATE NTLM");
+
+    if ((result = gen_recv(sock, msgbuf, sizeof msgbuf)))
+       return result;
+  
+    if (msgbuf[0] != '+')
+       return PS_AUTHFAIL;
+  
+    buildSmbNtlmAuthRequest(&request,ctl->remotename,NULL);
+
+    if (outlevel >= O_DEBUG)
+       dumpSmbNtlmAuthRequest(stdout, &request);
+
+    memset(msgbuf,0,sizeof msgbuf);
+    to64frombits (msgbuf, (unsigned char*)&request, SmbLength(&request));
+  
+    if (outlevel >= O_MONITOR)
+       report(stdout, "IMAP> %s\n", msgbuf);
+  
+    strcat(msgbuf,"\r\n");
+    SockWrite (sock, msgbuf, strlen (msgbuf));
+
+    if ((gen_recv(sock, msgbuf, sizeof msgbuf)))
+       return result;
+  
+    len = from64tobits ((unsigned char*)&challenge, msgbuf);
+    
+    if (outlevel >= O_DEBUG)
+       dumpSmbNtlmAuthChallenge(stdout, &challenge);
+    
+    buildSmbNtlmAuthResponse(&challenge, &response,ctl->remotename,ctl->password);
+  
+    if (outlevel >= O_DEBUG)
+       dumpSmbNtlmAuthResponse(stdout, &response);
+  
+    memset(msgbuf,0,sizeof msgbuf);
+    to64frombits (msgbuf, (unsigned char*)&response, SmbLength(&response));
+
+    if (outlevel >= O_MONITOR)
+       report(stdout, "IMAP> %s\n", msgbuf);
+      
+    strcat(msgbuf,"\r\n");
+
+    SockWrite (sock, msgbuf, strlen (msgbuf));
+  
+    if ((result = gen_recv (sock, msgbuf, sizeof msgbuf)))
+       return result;
+  
+    if (strstr (msgbuf, "OK"))
+       return PS_SUCCESS;
+    else
+       return PS_AUTHFAIL;
+}
+#endif /* NTLM */
 
 static int do_cram_md5 (int sock, struct query *ctl)
 /* authenticate as per RFC2195 */
@@ -683,7 +771,7 @@ static int do_cram_md5 (int sock, struct query *ctl)
      * [RFC822] as described in [POP3].
      */
 
-    if (result = gen_recv (sock, buf1, sizeof (buf1))) {
+    if ((result = gen_recv (sock, buf1, sizeof (buf1)))) {
        return result;
     }
 
@@ -731,10 +819,12 @@ static int do_cram_md5 (int sock, struct query *ctl)
     if (outlevel >= O_MONITOR) {
        report (stdout, "IMAP> %s\n", buf1);
     }
+
+    /* PMDF5.2 IMAP has a bug that requires this to be a single write */
+    strcat (buf1, "\r\n");
     SockWrite (sock, buf1, strlen (buf1));
-    SockWrite (sock, "\r\n", 2);
 
-    if (result = gen_recv (sock, buf1, sizeof (buf1)))
+    if ((result = gen_recv (sock, buf1, sizeof (buf1))))
        return result;
 
     if (strstr (buf1, "OK")) {
@@ -744,17 +834,17 @@ static int do_cram_md5 (int sock, struct query *ctl)
     }
 }
 
-int imap_canonicalize(char *result, char *passwd)
+int imap_canonicalize(char *result, char *raw, int maxlen)
 /* encode an IMAP password as per RFC1730's quoting conventions */
 {
     int i, j;
 
     j = 0;
-    for (i = 0; i < strlen(passwd); i++)
+    for (i = 0; i < strlen(raw) && i < maxlen; i++)
     {
-       if ((passwd[i] == '\\') || (passwd[i] == '"'))
+       if ((raw[i] == '\\') || (raw[i] == '"'))
            result[j++] = '\\';
-       result[j++] = passwd[i];
+       result[j++] = raw[i];
     }
     result[j] = '\0';
 
@@ -765,7 +855,6 @@ int imap_getauth(int sock, struct query *ctl, char *greeting)
 /* apply for connection authorization */
 {
     int ok = 0;
-    char       password[PASSWORDLEN*2];
 
     /* probe to see if we're running IMAP4 and can use RFC822.PEEK */
     capabilities[0] = '\0';
@@ -805,10 +894,14 @@ int imap_getauth(int sock, struct query *ctl, char *greeting)
     else
        expunge_period = 1;
 
-    if (preauth)
+    /* 
+     * If either (a) we saw a PREAUTH token in the capability response, or
+     * (b) the user specified ssh preauthentication, then we're done.
+     */
+    if (preauth || ctl->server.preauthenticate == A_SSH)
        return(PS_SUCCESS);
 
-#if OPIE
+#if OPIE_ENABLE
     if ((ctl->server.protocol == P_IMAP) && strstr(capabilities, "AUTH=X-OTP"))
     {
        if (outlevel >= O_DEBUG)
@@ -816,7 +909,7 @@ int imap_getauth(int sock, struct query *ctl, char *greeting)
        if (do_otp(sock, ctl) == PS_SUCCESS)
            return(PS_SUCCESS);
     };
-#endif /* OPIE */
+#endif /* OPIE_ENABLE */
 
 #ifdef GSSAPI
     if (strstr(capabilities, "AUTH=GSSAPI"))
@@ -863,19 +956,37 @@ int imap_getauth(int sock, struct query *ctl, char *greeting)
     }
 #endif /* KERBEROS_V4 */
 
-    if (strstr (capabilities, "AUTH=CRAM-MD5"))
+    if (strstr(capabilities, "AUTH=CRAM-MD5"))
     {
         if (outlevel >= O_DEBUG)
             report (stdout, _("CRAM-MD5 authentication is supported\n"));
-        if ((ok = do_cram_md5 (sock, ctl)))
+        if (ctl->server.protocol != P_IMAP_LOGIN)
         {
-            if (outlevel >= O_MONITOR)
-                report (stdout, "IMAP> *\n");
-            SockWrite (sock, "*\r\n", 3);
+            if ((ok = do_cram_md5 (sock, ctl)))
+            {
+                if (outlevel >= O_MONITOR)
+                    report (stdout, "IMAP> *\n");
+                SockWrite (sock, "*\r\n", 3);
+            }
+            return ok;
         }
-        return ok;
+    }
+    else if (ctl->server.protocol == P_IMAP_CRAM_MD5)
+    {
+        report(stderr,
+               _("Required CRAM-MD5 capability not supported by server\n"));
+        return(PS_AUTHFAIL);
     }
 
+#ifdef NTLM_ENABLE
+    if (strstr (capabilities, "AUTH=NTLM"))
+    {
+        if (outlevel >= O_DEBUG)
+            report (stdout, _("NTLM authentication is supported\n"));
+        return do_imap_ntlm (sock, ctl);
+    }
+#endif /* NTLM_ENABLE */
+
 #ifdef __UNUSED__      /* The Cyrus IMAP4rev1 server chokes on this */
     /* this handles either AUTH=LOGIN or AUTH-LOGIN */
     if ((imap_version >= IMAP4rev1) && (!strstr(capabilities, "LOGIN"))) {
@@ -885,8 +996,15 @@ int imap_getauth(int sock, struct query *ctl, char *greeting)
     };
 #endif /* __UNUSED__ */
 
-    imap_canonicalize(password, ctl->password);
-    ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", ctl->remotename, password);
+    {
+       /* these sizes guarantee no buffer overflow */
+       char    remotename[NAMELEN*2+1], password[PASSWORDLEN*2+1];
+
+       imap_canonicalize(remotename, ctl->remotename, NAMELEN);
+       imap_canonicalize(password, ctl->password, PASSWORDLEN);
+       ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", remotename, password);
+    }
+
     if (ok)
        return(ok);
     
@@ -1032,7 +1150,7 @@ static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
     number -= expunged;
 
     /*
-     * This is blessed by RFC 1176, RFC1730, RFC2060.
+     * This is blessed by RFC1176, RFC1730, RFC2060.
      * According to the RFCs, it should *not* set the \Seen flag.
      */
     gen_send(sock, "FETCH %d RFC822.HEADER", number);
@@ -1069,7 +1187,8 @@ static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
      *
      * However...*don't* do this if we're using keep to suppress deletion!
      * In that case, marking the seen flag is the only way to prevent the
-     * message from being re-fetched on subsequent runs.
+     * message from being re-fetched on subsequent runs (and according
+     * to RFC2060 p.43 this fetch should set Seen as a side effect).
      */
     switch (imap_version)
     {
@@ -1104,11 +1223,15 @@ static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
     if (num != number)
        return(PS_ERROR);
 
-    /* try to extract a length */
+    /*
+     * Try to extract a length from the FETCH response.  RFC2060 requires
+     * it to be present, but at least one IMAP server (Novell GroupWise)
+     * botches this.
+     */
     if ((cp = strchr(buf, '{')))
        *lenp = atoi(cp + 1);
     else
-       *lenp = 0;
+       *lenp = -1;     /* missing length part in FETCH reponse */
 
     return(PS_SUCCESS);
 }
@@ -1130,6 +1253,26 @@ static int imap_trail(int sock, struct query *ctl, int number)
        /* UW IMAP returns "OK FETCH", Cyrus returns "OK Completed" */
        if (strstr(buf, "OK"))
            break;
+
+#ifdef __UNUSED__
+       /*
+        * Any IMAP server that fails to set Seen on a BODY[TEXT]
+        * fetch violates RFC2060 p.43 (top).  This becomes an issue
+        * when keep is on, because seen messages aren't deleted and
+        * get refetched on each poll.  As a workaround, if keep is on
+        * we can set the Seen flag explicitly.
+        *
+        * This code isn't used yet because we don't know of any IMAP
+        * servers broken in this way.
+        */
+       if (ctl->keep)
+           if ((ok = gen_transact(sock,
+                       imap_version == IMAP4 
+                               ? "STORE %d +FLAGS.SILENT (\\Seen)"
+                               : "STORE %d +FLAGS (\\Seen)", 
+                       number)))
+               return(ok);
+#endif /* __UNUSED__ */
     }
 
     return(PS_SUCCESS);
@@ -1187,18 +1330,20 @@ static int imap_logout(int sock, struct query *ctl)
 const static struct method imap =
 {
     "IMAP",            /* Internet Message Access Protocol */
-#if INET6
+#if INET6_ENABLE
     "imap",
-#else /* INET6 */
+    "imaps",
+#else /* INET6_ENABLE */
     143,                /* standard IMAP2bis/IMAP4 port */
-#endif /* INET6 */
+    993,                /* ssl IMAP2bis/IMAP4 port */
+#endif /* INET6_ENABLE */
     TRUE,              /* this is a tagged protocol */
     FALSE,             /* no message delimiter */
     imap_ok,           /* parse command response */
     imap_canonicalize, /* deal with embedded slashes and spaces */
     imap_getauth,      /* get authorization */
     imap_getrange,     /* query range of messages */
-    imap_getsizes,     /* get sizes of messages (used for --limit option */
+    imap_getsizes,     /* get sizes of messages (used for ESMTP SIZE option) */
     imap_is_old,       /* no UID check */
     imap_fetch_headers,        /* request given message headers */
     imap_fetch_body,   /* request given message body */