1 /**
2  * @file
3  * SASL plain authentication support
4  *
5  * @authors
6  * Copyright (C) 2016 Pietro Cerutti <gahr@gahr.ch>
7  *
8  * @copyright
9  * This program is free software: you can redistribute it and/or modify it under
10  * the terms of the GNU General Public License as published by the Free Software
11  * Foundation, either version 2 of the License, or (at your option) any later
12  * version.
13  *
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
17  * details.
18  *
19  * You should have received a copy of the GNU General Public License along with
20  * this program.  If not, see <http://www.gnu.org/licenses/>.
21  */
22 
23 /**
24  * @page conn_sasl_plain SASL plain authentication
25  *
26  * SASL plain authentication support
27  */
28 
29 #include "config.h"
30 #include <stdio.h>
31 #include "mutt/lib.h"
32 #include "sasl_plain.h"
33 
34 /**
35  * mutt_sasl_plain_msg - Construct a base64 encoded SASL PLAIN message
36  * @param buf    Destination buffer
37  * @param buflen Available space in the destination buffer
38  * @param cmd    Protocol-specific string the prepend to the PLAIN message
39  * @param authz  Authorization identity
40  * @param user   Authentication identity (username)
41  * @param pass   Password
42  * @retval >0 Success, number of chars in the command string
43  * @retval  0 Error
44  *
45  * This function can be used to build a protocol-specific SASL Response message
46  * using the PLAIN mechanism. The protocol specific command is given in the cmd
47  * parameter. The function appends a space, encodes the string derived from
48  * authz\0user\0pass using base64 encoding, and stores the result in buf. If
49  * cmd is either NULL or the empty string, the initial space is skipped.
50  *
51  * authz, user, and pass can each be up to 255 bytes, making up for a 765 bytes
52  * string. Add the two NULL bytes in between plus one at the end and we get
53  * 768.
54  */
mutt_sasl_plain_msg(char * buf,size_t buflen,const char * cmd,const char * authz,const char * user,const char * pass)55 size_t mutt_sasl_plain_msg(char *buf, size_t buflen, const char *cmd,
56                            const char *authz, const char *user, const char *pass)
57 {
58   char tmp[768];
59   size_t len = 0;
60   size_t tmplen;
61 
62   if (!user || (*user == '\0') || !pass || (*pass == '\0'))
63     return 0;
64 
65   tmplen = snprintf(tmp, sizeof(tmp), "%s%c%s%c%s", NONULL(authz), '\0', user, '\0', pass);
66 
67   if (cmd && *cmd)
68   {
69     len = snprintf(buf, buflen, "%s ", cmd);
70   }
71   len += mutt_b64_encode(tmp, tmplen, buf + len, buflen - len);
72   return len;
73 }
74