update version
[openssh.git] / auth2-pubkey.c
1 /* $OpenBSD: auth2-pubkey.c,v 1.29 2011/05/23 03:30:07 djm Exp $ */
2 /*
3  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "includes.h"
27
28 #include <sys/types.h>
29 #include <sys/stat.h>
30
31 #include <fcntl.h>
32 #include <pwd.h>
33 #include <stdio.h>
34 #include <stdarg.h>
35 #include <string.h>
36 #include <time.h>
37 #include <unistd.h>
38
39 #include "xmalloc.h"
40 #include "ssh.h"
41 #include "ssh2.h"
42 #include "packet.h"
43 #include "buffer.h"
44 #include "log.h"
45 #include "servconf.h"
46 #include "compat.h"
47 #include "key.h"
48 #include "hostfile.h"
49 #include "auth.h"
50 #include "pathnames.h"
51 #include "uidswap.h"
52 #include "auth-options.h"
53 #include "canohost.h"
54 #ifdef GSSAPI
55 #include "ssh-gss.h"
56 #endif
57 #include "monitor_wrap.h"
58 #include "misc.h"
59 #include "authfile.h"
60 #include "match.h"
61
62 /* import */
63 extern ServerOptions options;
64 extern u_char *session_id2;
65 extern u_int session_id2_len;
66
67 static int
68 userauth_pubkey(Authctxt *authctxt)
69 {
70         Buffer b;
71         Key *key = NULL;
72         char *pkalg;
73         u_char *pkblob, *sig;
74         u_int alen, blen, slen;
75         int have_sig, pktype;
76         int authenticated = 0;
77
78         if (!authctxt->valid) {
79                 debug2("userauth_pubkey: disabled because of invalid user");
80                 return 0;
81         }
82         have_sig = packet_get_char();
83         if (datafellows & SSH_BUG_PKAUTH) {
84                 debug2("userauth_pubkey: SSH_BUG_PKAUTH");
85                 /* no explicit pkalg given */
86                 pkblob = packet_get_string(&blen);
87                 buffer_init(&b);
88                 buffer_append(&b, pkblob, blen);
89                 /* so we have to extract the pkalg from the pkblob */
90                 pkalg = buffer_get_string(&b, &alen);
91                 buffer_free(&b);
92         } else {
93                 pkalg = packet_get_string(&alen);
94                 pkblob = packet_get_string(&blen);
95         }
96         pktype = key_type_from_name(pkalg);
97         if (pktype == KEY_UNSPEC) {
98                 /* this is perfectly legal */
99                 logit("userauth_pubkey: unsupported public key algorithm: %s",
100                     pkalg);
101                 goto done;
102         }
103         key = key_from_blob(pkblob, blen);
104         if (key == NULL) {
105                 error("userauth_pubkey: cannot decode key: %s", pkalg);
106                 goto done;
107         }
108         if (key->type != pktype) {
109                 error("userauth_pubkey: type mismatch for decoded key "
110                     "(received %d, expected %d)", key->type, pktype);
111                 goto done;
112         }
113         if (have_sig) {
114                 sig = packet_get_string(&slen);
115                 packet_check_eom();
116                 buffer_init(&b);
117                 if (datafellows & SSH_OLD_SESSIONID) {
118                         buffer_append(&b, session_id2, session_id2_len);
119                 } else {
120                         buffer_put_string(&b, session_id2, session_id2_len);
121                 }
122                 /* reconstruct packet */
123                 buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
124                 buffer_put_cstring(&b, authctxt->user);
125                 buffer_put_cstring(&b,
126                     datafellows & SSH_BUG_PKSERVICE ?
127                     "ssh-userauth" :
128                     authctxt->service);
129                 if (datafellows & SSH_BUG_PKAUTH) {
130                         buffer_put_char(&b, have_sig);
131                 } else {
132                         buffer_put_cstring(&b, "publickey");
133                         buffer_put_char(&b, have_sig);
134                         buffer_put_cstring(&b, pkalg);
135                 }
136                 buffer_put_string(&b, pkblob, blen);
137 #ifdef DEBUG_PK
138                 buffer_dump(&b);
139 #endif
140                 /* test for correct signature */
141                 authenticated = 0;
142                 if (PRIVSEP(user_key_allowed(authctxt->pw, key)) &&
143                     PRIVSEP(key_verify(key, sig, slen, buffer_ptr(&b),
144                     buffer_len(&b))) == 1)
145                         authenticated = 1;
146                 buffer_free(&b);
147                 xfree(sig);
148         } else {
149                 debug("test whether pkalg/pkblob are acceptable");
150                 packet_check_eom();
151
152                 /* XXX fake reply and always send PK_OK ? */
153                 /*
154                  * XXX this allows testing whether a user is allowed
155                  * to login: if you happen to have a valid pubkey this
156                  * message is sent. the message is NEVER sent at all
157                  * if a user is not allowed to login. is this an
158                  * issue? -markus
159                  */
160                 if (PRIVSEP(user_key_allowed(authctxt->pw, key))) {
161                         packet_start(SSH2_MSG_USERAUTH_PK_OK);
162                         packet_put_string(pkalg, alen);
163                         packet_put_string(pkblob, blen);
164                         packet_send();
165                         packet_write_wait();
166                         authctxt->postponed = 1;
167                 }
168         }
169         if (authenticated != 1)
170                 auth_clear_options();
171 done:
172         debug2("userauth_pubkey: authenticated %d pkalg %s", authenticated, pkalg);
173         if (key != NULL)
174                 key_free(key);
175         xfree(pkalg);
176         xfree(pkblob);
177         return authenticated;
178 }
179
180 static int
181 match_principals_option(const char *principal_list, struct KeyCert *cert)
182 {
183         char *result;
184         u_int i;
185
186         /* XXX percent_expand() sequences for authorized_principals? */
187
188         for (i = 0; i < cert->nprincipals; i++) {
189                 if ((result = match_list(cert->principals[i],
190                     principal_list, NULL)) != NULL) {
191                         debug3("matched principal from key options \"%.100s\"",
192                             result);
193                         xfree(result);
194                         return 1;
195                 }
196         }
197         return 0;
198 }
199
200 static int
201 match_principals_file(char *file, struct passwd *pw, struct KeyCert *cert)
202 {
203         FILE *f;
204         char line[SSH_MAX_PUBKEY_BYTES], *cp, *ep, *line_opts;
205         u_long linenum = 0;
206         u_int i;
207
208         temporarily_use_uid(pw);
209         debug("trying authorized principals file %s", file);
210         if ((f = auth_openprincipals(file, pw, options.strict_modes)) == NULL) {
211                 restore_uid();
212                 return 0;
213         }
214         auth_start_parse_options();
215         while (read_keyfile_line(f, file, line, sizeof(line), &linenum) != -1) {
216                 /* Skip leading whitespace. */
217                 for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
218                         ;
219                 /* Skip blank and comment lines. */
220                 if ((ep = strchr(cp, '#')) != NULL)
221                         *ep = '\0';
222                 if (!*cp || *cp == '\n')
223                         continue;
224                 /* Trim trailing whitespace. */
225                 ep = cp + strlen(cp) - 1;
226                 while (ep > cp && (*ep == '\n' || *ep == ' ' || *ep == '\t'))
227                         *ep-- = '\0';
228                 /*
229                  * If the line has internal whitespace then assume it has
230                  * key options.
231                  */
232                 line_opts = NULL;
233                 if ((ep = strrchr(cp, ' ')) != NULL ||
234                     (ep = strrchr(cp, '\t')) != NULL) {
235                         for (; *ep == ' ' || *ep == '\t'; ep++)
236                                 ;
237                         line_opts = cp;
238                         cp = ep;
239                 }
240                 for (i = 0; i < cert->nprincipals; i++) {
241                         if (strcmp(cp, cert->principals[i]) == 0) {
242                                 debug3("matched principal from file \"%.100s\"",
243                                     cert->principals[i]);
244                                 if (auth_parse_options(pw, line_opts,
245                                     file, linenum) != 1)
246                                         continue;
247                                 fclose(f);
248                                 restore_uid();
249                                 return 1;
250                         }
251                 }
252         }
253         fclose(f);
254         restore_uid();
255         return 0;
256 }       
257
258 /* return 1 if user allows given key */
259 static int
260 user_key_allowed2(struct passwd *pw, Key *key, char *file)
261 {
262         char line[SSH_MAX_PUBKEY_BYTES];
263         const char *reason;
264         int found_key = 0;
265         FILE *f;
266         u_long linenum = 0;
267         Key *found;
268         char *fp;
269
270         /* Temporarily use the user's uid. */
271         temporarily_use_uid(pw);
272
273         debug("trying public key file %s", file);
274         f = auth_openkeyfile(file, pw, options.strict_modes);
275
276         if (!f) {
277                 restore_uid();
278                 return 0;
279         }
280
281         found_key = 0;
282         found = key_new(key_is_cert(key) ? KEY_UNSPEC : key->type);
283
284         auth_start_parse_options();
285
286         while (read_keyfile_line(f, file, line, sizeof(line), &linenum) != -1) {
287                 char *cp, *key_options = NULL;
288
289                 auth_clear_options();
290
291                 /* Skip leading whitespace, empty and comment lines. */
292                 for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
293                         ;
294                 if (!*cp || *cp == '\n' || *cp == '#')
295                         continue;
296
297                 if (key_read(found, &cp) != 1) {
298                         /* no key?  check if there are options for this key */
299                         int quoted = 0;
300                         debug2("user_key_allowed: check options: '%s'", cp);
301                         key_options = cp;
302                         for (; *cp && (quoted || (*cp != ' ' && *cp != '\t')); cp++) {
303                                 if (*cp == '\\' && cp[1] == '"')
304                                         cp++;   /* Skip both */
305                                 else if (*cp == '"')
306                                         quoted = !quoted;
307                         }
308                         /* Skip remaining whitespace. */
309                         for (; *cp == ' ' || *cp == '\t'; cp++)
310                                 ;
311                         if (key_read(found, &cp) != 1) {
312                                 debug2("user_key_allowed: advance: '%s'", cp);
313                                 /* still no key?  advance to next line*/
314                                 continue;
315                         }
316                 }
317                 if (key_is_cert(key)) {
318                         if (!key_equal(found, key->cert->signature_key))
319                                 continue;
320                         if (auth_parse_options(pw, key_options, file,
321                             linenum) != 1)
322                                 continue;
323                         if (!key_is_cert_authority)
324                                 continue;
325                         fp = key_fingerprint(found, SSH_FP_MD5,
326                             SSH_FP_HEX);
327                         debug("matching CA found: file %s, line %lu, %s %s",
328                             file, linenum, key_type(found), fp);
329                         /*
330                          * If the user has specified a list of principals as
331                          * a key option, then prefer that list to matching
332                          * their username in the certificate principals list.
333                          */
334                         if (authorized_principals != NULL &&
335                             !match_principals_option(authorized_principals,
336                             key->cert)) {
337                                 reason = "Certificate does not contain an "
338                                     "authorized principal";
339  fail_reason:
340                                 xfree(fp);
341                                 error("%s", reason);
342                                 auth_debug_add("%s", reason);
343                                 continue;
344                         }
345                         if (key_cert_check_authority(key, 0, 0,
346                             authorized_principals == NULL ? pw->pw_name : NULL,
347                             &reason) != 0)
348                                 goto fail_reason;
349                         if (auth_cert_options(key, pw) != 0) {
350                                 xfree(fp);
351                                 continue;
352                         }
353                         verbose("Accepted certificate ID \"%s\" "
354                             "signed by %s CA %s via %s", key->cert->key_id,
355                             key_type(found), fp, file);
356                         xfree(fp);
357                         found_key = 1;
358                         break;
359                 } else if (key_equal(found, key)) {
360                         if (auth_parse_options(pw, key_options, file,
361                             linenum) != 1)
362                                 continue;
363                         if (key_is_cert_authority)
364                                 continue;
365                         found_key = 1;
366                         debug("matching key found: file %s, line %lu",
367                             file, linenum);
368                         fp = key_fingerprint(found, SSH_FP_MD5, SSH_FP_HEX);
369                         verbose("Found matching %s key: %s",
370                             key_type(found), fp);
371                         xfree(fp);
372                         break;
373                 }
374         }
375         restore_uid();
376         fclose(f);
377         key_free(found);
378         if (!found_key)
379                 debug2("key not found");
380         return found_key;
381 }
382
383 /* Authenticate a certificate key against TrustedUserCAKeys */
384 static int
385 user_cert_trusted_ca(struct passwd *pw, Key *key)
386 {
387         char *ca_fp, *principals_file = NULL;
388         const char *reason;
389         int ret = 0;
390
391         if (!key_is_cert(key) || options.trusted_user_ca_keys == NULL)
392                 return 0;
393
394         ca_fp = key_fingerprint(key->cert->signature_key,
395             SSH_FP_MD5, SSH_FP_HEX);
396
397         if (key_in_file(key->cert->signature_key,
398             options.trusted_user_ca_keys, 1) != 1) {
399                 debug2("%s: CA %s %s is not listed in %s", __func__,
400                     key_type(key->cert->signature_key), ca_fp,
401                     options.trusted_user_ca_keys);
402                 goto out;
403         }
404         /*
405          * If AuthorizedPrincipals is in use, then compare the certificate
406          * principals against the names in that file rather than matching
407          * against the username.
408          */
409         if ((principals_file = authorized_principals_file(pw)) != NULL) {
410                 if (!match_principals_file(principals_file, pw, key->cert)) {
411                         reason = "Certificate does not contain an "
412                             "authorized principal";
413  fail_reason:
414                         error("%s", reason);
415                         auth_debug_add("%s", reason);
416                         goto out;
417                 }
418         }
419         if (key_cert_check_authority(key, 0, 1,
420             principals_file == NULL ? pw->pw_name : NULL, &reason) != 0)
421                 goto fail_reason;
422         auth_start_parse_options();
423         if (auth_cert_options(key, pw) != 0)
424                 goto out;
425
426         verbose("Accepted certificate ID \"%s\" signed by %s CA %s via %s",
427             key->cert->key_id, key_type(key->cert->signature_key), ca_fp,
428             options.trusted_user_ca_keys);
429         ret = 1;
430
431  out:
432         if (principals_file != NULL)
433                 xfree(principals_file);
434         if (ca_fp != NULL)
435                 xfree(ca_fp);
436         return ret;
437 }
438
439 /* check whether given key is in .ssh/authorized_keys* */
440 int
441 user_key_allowed(struct passwd *pw, Key *key)
442 {
443         u_int success, i;
444         char *file;
445
446         if (auth_key_is_revoked(key, 0))
447                 return 0;
448         if (key_is_cert(key) &&
449             auth_key_is_revoked(key->cert->signature_key, 0))
450                 return 0;
451
452         success = user_cert_trusted_ca(pw, key);
453         if (success)
454                 return success;
455
456         for (i = 0; !success && i < options.num_authkeys_files; i++) {
457                 file = expand_authorized_keys(
458                     options.authorized_keys_files[i], pw);
459                 success = user_key_allowed2(pw, key, file);
460                 xfree(file);
461         }
462
463         return success;
464 }
465
466 Authmethod method_pubkey = {
467         "publickey",
468         userauth_pubkey,
469         &options.pubkey_authentication
470 };