919540f549ada10c471b06c9fb64bb928a3f257c
[cifs-utils.git] / cifskey.c
1 /*
2  * Credentials stashing routines for Linux CIFS VFS (virtual filesystem)
3  * Copyright (C) 2010 Jeff Layton (jlayton@samba.org)
4  * Copyright (C) 2010 Igor Druzhinin (jaxbrigs@gmail.com)
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include <sys/types.h>
21 #include <keyutils.h>
22 #include <stdio.h>
23 #include <errno.h>
24 #include "cifskey.h"
25 #include "resolve_host.h"
26
27 /* search a specific key in keyring */
28 key_serial_t
29 key_search(const char *addr, char keytype)
30 {
31         char desc[INET6_ADDRSTRLEN + sizeof(KEY_PREFIX) + 4];
32
33         if (snprintf(desc, sizeof(desc), "%s:%c:%s", KEY_PREFIX, keytype, addr) >= (int)sizeof(desc)) {
34                 errno = EINVAL;
35                 return -1;
36         }
37
38         return keyctl_search(DEST_KEYRING, CIFS_KEY_TYPE, desc, 0);
39 }
40
41 /* add or update a specific key to keyring */
42 key_serial_t
43 key_add(const char *addr, const char *user, const char *pass, char keytype)
44 {
45         int len;
46         char desc[INET6_ADDRSTRLEN + sizeof(KEY_PREFIX) + 4];
47         char val[MOUNT_PASSWD_SIZE +  MAX_USERNAME_SIZE + 2];
48
49         /* set key description */
50         if (snprintf(desc, sizeof(desc), "%s:%c:%s", KEY_PREFIX, keytype, addr) >= (int)sizeof(desc)) {
51                 errno = EINVAL;
52                 return -1;
53         }
54
55         /* set payload contents */
56         len = snprintf(val, sizeof(val), "%s:%s", user, pass);
57         if (len >= (int)sizeof(val)) {
58                 errno = EINVAL;
59                 return -1;
60         }
61
62         return add_key(CIFS_KEY_TYPE, desc, val, len + 1, DEST_KEYRING);
63 }