Exemple #1
0
int
main(int argc, char **argv)
{
    krb5_keyblock keyblock;
    krb5_error_code ret;
    krb5_context context;
    krb5_crypto crypto;
    int i;

    ret = krb5_init_context(&context);
    if (ret)
	errx(1, "krb5_context_init: %d", ret);

    ret = krb5_generate_random_keyblock(context,
					ENCTYPE_AES256_CTS_HMAC_SHA1_96,
					&keyblock);
    if (ret)
	krb5_err(context, 1, ret, "krb5_generate_random_keyblock");

    ret = krb5_crypto_init(context, &keyblock, 0, &crypto);
    if (ret)
	krb5_err(context, 1, ret, "krb5_crypto_init");

    test_special(context, crypto, 1, 60);
    test_special(context, crypto, 0, 60);

    for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++) {
	test_range(&tests[i], 1, context, crypto);
	test_range(&tests[i], 0, context, crypto);
    }

    krb5_free_keyblock_contents(context, &keyblock);
    krb5_crypto_destroy(context, crypto);
    krb5_free_context(context);

    return 0;
}
Exemple #2
0
static void
krb5_init(void)
{
    krb5_context context;
    krb5_error_code ret;
    krb5_boolean ret_val;

    ret = krb5_init_context(&context);
    if (ret)
	return;

#if defined(AUTHENTICATION) && defined(FORWARD)
    krb5_appdefault_boolean(context, NULL,
			    NULL, "forward",
			    0, &ret_val);
    if (ret_val)
	    kerberos5_set_forward(1);
    krb5_appdefault_boolean(context, NULL,
			    NULL, "forwardable",
			    0, &ret_val);
    if (ret_val)
	    kerberos5_set_forwardable(1);
#endif
#ifdef  ENCRYPTION
    krb5_appdefault_boolean(context, NULL,
			    NULL, "encrypt",
			    0, &ret_val);
    if (ret_val) {
          encrypt_auto(1);
          decrypt_auto(1);
	  wantencryption = 1;
          EncryptVerbose(1);
        }
#endif

    krb5_free_context(context);
}
Exemple #3
0
int
main (int argc, char **argv)
{
    int optidx = 0;
    krb5_error_code ret;
    krb5_context context;
    krb5_keytab kt;

    setprogname (argv[0]);

    ret = krb5_init_context (&context);
    if (ret)
	errx(1, "krb5_init_context failed: %u", ret);

    if (getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
	usage(1);

    if (help_flag)
	usage(0);

    if (version_flag) {
	print_version(NULL);
	return 0;
    }

    if (enctype_string)
	enc_type = enctype_string;

    setup_env(context, &kt);

    if (use_krb5)
	create_krb5_tickets(context, kt);

    krb5_kt_close(context, kt);

    return 0;
}
Exemple #4
0
/**
 * python-krb5 initialization function.
 */
PyMODINIT_FUNC initkrb5(void)
{
	PyObject *module;
	krb5_error_code rc;
   
	if(PyType_Ready(&PrincipalType) < 0)
		return;
	if(PyType_Ready(&CredentialType) < 0)
		return;

	module = Py_InitModule("krb5", krb5_methods);

	if(module == NULL)
		return;
		
	/* define Krb5Error exception */
	//Krb5Error = PyErr_NewException("krb5.Krb5Error", NULL, NULL);
	//Py_INCREF(Krb5Error);
	//PyModule_AddObject(module, "error", Krb5Error);

	/* initialize kerberos */
	rc = krb5_init_context(&module_context);
	if(rc) {
		return;
	}

	/* Add the Principal object */
	Py_INCREF(&PrincipalType);
	PyModule_AddObject(module, "Principal", (PyObject *)&PrincipalType);

	/* Add the Credential object */
	Py_INCREF(&CredentialType);
	PyModule_AddObject(module, "Credential", (PyObject *)&CredentialType);

	/* define module cleanup function */
	Py_AtExit(cleanup);
}
Exemple #5
0
DWORD
LwKrb5GetDefaultCachePath(
    OUT PSTR* ppszCachePath
    )
{
    DWORD dwError = 0;
    PSTR  pszCachePath = NULL;
    krb5_context ctx = NULL;
    const char *pszKrbDefault = NULL;
    krb5_error_code ret = 0;
    
    ret = krb5_init_context(&ctx);
    BAIL_ON_KRB_ERROR(ctx, ret);

    pszKrbDefault = krb5_cc_default_name(ctx);

    dwError = LwAllocateString(
                pszKrbDefault,
                &pszCachePath);
    BAIL_ON_LW_ERROR(dwError);
    
    *ppszCachePath = pszCachePath;
    
cleanup:
    if (ctx)
    {
        krb5_free_context(ctx);
    }

    return dwError;
    
error:

    *ppszCachePath = NULL;
    
    goto cleanup;
}
Exemple #6
0
/*
 * Called upon exit.  Destroys machine credentials.
 */
void
gssd_destroy_krb5_machine_creds(void)
{
	krb5_context context;
	krb5_error_code code = 0;
	krb5_ccache ccache;
	struct gssd_k5_kt_princ *ple;
	char *k5err = NULL;

	code = krb5_init_context(&context);
	if (code) {
		k5err = gssd_k5_err_msg(NULL, code);
		printerr(0, "ERROR: %s while initializing krb5\n", k5err);
		goto out;
	}

	for (ple = gssd_k5_kt_princ_list; ple; ple = ple->next) {
		if (!ple->ccname)
			continue;
		if ((code = krb5_cc_resolve(context, ple->ccname, &ccache))) {
			k5err = gssd_k5_err_msg(context, code);
			printerr(0, "WARNING: %s while resolving credential "
				    "cache '%s' for destruction\n", k5err,
				    ple->ccname);
			continue;
		}

		if ((code = krb5_cc_destroy(context, ccache))) {
			k5err = gssd_k5_err_msg(context, code);
			printerr(0, "WARNING: %s while destroying credential "
				    "cache '%s'\n", k5err, ple->ccname);
		}
	}
  out:
	free(k5err);
	krb5_free_context(context);
}
Exemple #7
0
static void
test_mcc_default(void)
{
    krb5_context context;
    krb5_error_code ret;
    krb5_ccache id, id2;
    int i;

    for (i = 0; i < 10; i++) {

	ret = krb5_init_context(&context);
	if (ret)
	    krb5_err(context, 1, ret, "krb5_init_context");

	ret = krb5_cc_set_default_name(context, "MEMORY:foo");
	if (ret)
	    krb5_err(context, 1, ret, "krb5_cc_set_default_name");

	ret = krb5_cc_default(context, &id);
	if (ret)
	    krb5_err(context, 1, ret, "krb5_cc_default");

	ret = krb5_cc_default(context, &id2);
	if (ret)
	    krb5_err(context, 1, ret, "krb5_cc_default");

	ret = krb5_cc_close(context, id);
	if (ret)
	    krb5_err(context, 1, ret, "krb5_cc_close");

	ret = krb5_cc_close(context, id2);
	if (ret)
	    krb5_err(context, 1, ret, "krb5_cc_close");

	krb5_free_context(context);
    }
}
Exemple #8
0
/*
 * check for the most common configuration errors.
 *
 * The errors checked for are:
 *   - tkey-gssapi-credential doesn't start with DNS/
 *   - the default realm in /etc/krb5.conf and the
 *     tkey-gssapi-credential bind config option don't match
 *
 * Note that if tkey-gssapi-keytab is set then these configure checks
 * are not performed, and runtime errors from gssapi are used instead
 */
static void
check_config(const char *gss_name) {
	const char *p;
	krb5_context krb5_ctx;
	char *krb5_realm_name = NULL;

	if (strncasecmp(gss_name, "DNS/", 4) != 0) {
		gss_log(ISC_LOG_ERROR, "tkey-gssapi-credential (%s) "
			"should start with 'DNS/'", gss_name);
		return;
	}

	if (krb5_init_context(&krb5_ctx) != 0) {
		gss_log(ISC_LOG_ERROR, "Unable to initialise krb5 context");
		return;
	}
	if (krb5_get_default_realm(krb5_ctx, &krb5_realm_name) != 0) {
		gss_log(ISC_LOG_ERROR, "Unable to get krb5 default realm");
		krb5_free_context(krb5_ctx);
		return;
	}
	p = strchr(gss_name, '@');
	if (p == NULL) {
		gss_log(ISC_LOG_ERROR, "badly formatted "
			"tkey-gssapi-credentials (%s)", gss_name);
		krb5_free_context(krb5_ctx);
		return;
	}
	if (strcasecmp(p + 1, krb5_realm_name) != 0) {
		gss_log(ISC_LOG_ERROR, "default realm from krb5.conf (%s) "
			"does not match tkey-gssapi-credential (%s)",
			krb5_realm_name, gss_name);
		krb5_free_context(krb5_ctx);
		return;
	}
	krb5_free_context(krb5_ctx);
}
Exemple #9
0
int
main(int argc, char **argv)
{
    krb5_context context;
    krb5_error_code ret;
    int i, optidx = 0;

    setprogname(argv[0]);

    if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
	usage(1);

    if (help_flag)
	usage (0);

    if(version_flag){
	print_version(NULL);
	exit(0);
    }

    argc -= optidx;
    argv += optidx;

    ret = krb5_init_context(&context);
    if (ret)
	errx (1, "krb5_init_context failed: %d", ret);

    for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++) {
	test_dh2key(i, context, &tests[i].X, NULL, NULL,
		    tests[i].type, &tests[i].key);
    }

    krb5_free_context(context);

    return 0;
}
Exemple #10
0
krb5_error_code
_gsskrb5_init (void)
{
    krb5_error_code ret = 0;

    HEIMDAL_MUTEX_lock(&_gsskrb5_context_mutex);

    if(_gsskrb5_context == NULL)
	ret = krb5_init_context (&_gsskrb5_context);
    if (ret == 0 && !created_key) {
	HEIMDAL_key_create(&gssapi_context_key, 
			   gssapi_destroy_thread_context,
			   ret);
	if (ret) {
	    krb5_free_context(_gsskrb5_context);
	    _gsskrb5_context = NULL;
	} else
	    created_key = 1;
    }

    HEIMDAL_MUTEX_unlock(&_gsskrb5_context_mutex);

    return ret;
}
Exemple #11
0
int
main()
{
    size_t i;
    struct test *t;
    krb5_principal matching, princ;
    krb5_context ctx;

    if (krb5_init_context(&ctx) != 0)
        abort();
    for (i = 0; i < sizeof(tests) / sizeof(*tests); i++) {
        t = &tests[i];

        if (t->matchstr != NULL) {
            if (krb5_parse_name(ctx, t->matchstr, &matching) != 0)
                abort();
            if (t->non_host_nametype)
                matching->type = KRB5_NT_PRINCIPAL;
            else
                matching->type = KRB5_NT_SRV_HST;
        } else {
            matching = NULL;
        }
        if (krb5_parse_name(ctx, t->princstr, &princ) != 0)
            abort();

        ctx->ignore_acceptor_hostname = t->ignore_acceptor_hostname;
        if (krb5_sname_match(ctx, matching, princ) != t->result)
            abort();

        krb5_free_principal(ctx, matching);
        krb5_free_principal(ctx, princ);
    }
    krb5_free_context(ctx);
    return 0;
}
Exemple #12
0
static PyObject *
k5_cc_copy_creds(PyObject *self, PyObject *args)
{
    krb5_context ctx;
    char *namein, *nameout;
    krb5_error_code code;
    krb5_ccache ccin, ccout;
    krb5_principal principal;

    if (!PyArg_ParseTuple( args, "ss", &namein, &nameout))
	return NULL;

    code = krb5_init_context(&ctx);
    RETURN_ON_ERROR("krb5_init_context()", code);
    code = krb5_cc_resolve(ctx, namein, &ccin);
    RETURN_ON_ERROR("krb5_cc_resolve()", code);
    code = krb5_cc_get_principal(ctx, ccin, &principal);
    RETURN_ON_ERROR("krb5_cc_get_principal()", code);

    code = krb5_cc_resolve(ctx, nameout, &ccout);
    RETURN_ON_ERROR("krb5_cc_resolve()", code);
    code = krb5_cc_initialize(ctx, ccout, principal);
    RETURN_ON_ERROR("krb5_cc_get_initialize()", code);
    code = krb5_cc_copy_creds(ctx, ccin, ccout);
    RETURN_ON_ERROR("krb5_cc_copy_creds()", code);

    code = krb5_cc_close(ctx, ccin);
    RETURN_ON_ERROR("krb5_cc_close()", code);
    code = krb5_cc_close(ctx, ccout);
    RETURN_ON_ERROR("krb5_cc_close()", code);
    krb5_free_principal(ctx, principal);
    krb5_free_context(ctx);

    Py_INCREF(Py_None);
    return Py_None;
}
Exemple #13
0
kim_error kim_identity_create_from_string (kim_identity *out_identity,
                                           kim_string    in_string)
{
    kim_error err = KIM_NO_ERROR;
    kim_identity identity = NULL;

    if (!err && !out_identity) { err = check_error (KIM_NULL_PARAMETER_ERR); }
    if (!err && !in_string   ) { err = check_error (KIM_NULL_PARAMETER_ERR); }

    if (!err) {
        err = kim_identity_allocate (&identity);
    }

    if (!err) {
        err = krb5_error (NULL, krb5_init_context (&identity->context));
    }

    if (!err) {
        krb5_error_code code = krb5_parse_name (identity->context, in_string, &identity->principal);
        if (code == KRB5_PARSE_MALFORMED) {
            err = kim_error_set_message_for_code (KIM_BAD_PRINCIPAL_STRING_ERR,
                                                  in_string);
        } else if (code) {
            err = krb5_error (identity->context, code);
        }
    }

    if (!err) {
        *out_identity = identity;
        identity = NULL;
    }

    if (identity) { kim_identity_free (&identity); }

    return check_error (err);
}
Exemple #14
0
Fichier : gss.c Projet : B1NG0/cifs
static char *
get_realm(void)
{
	int error;
	krb5_context ctx;
	const char *msg;
	char *realm;

	error = krb5_init_context(&ctx);
	if (error) {
		smb_log_info("%s: Couldn't initialize kerberos: %d", ASL_LEVEL_DEBUG, __FUNCTION__, error);
		return (NULL);
	}		
	error = krb5_get_default_realm(ctx, &realm);
	if (error) {
		msg = krb5_get_error_message(ctx, error);
		smb_log_info("%s: Couldn't get kerberos default realm: %s", ASL_LEVEL_DEBUG, __FUNCTION__, msg);
		krb5_free_error_message(ctx, msg);
		return (NULL);
	}		
	krb5_free_context(ctx);
	
	return (realm);
}
int
main(int argc, char **argv)
{
    krb5_error_code ret;
    krb5_context context;
    krb5_principal principal;

    ret = krb5_init_context(&context);
    if (ret)
	errx(1, "krb5_init_context");

    ret = krb5_parse_name(context, "*****@*****.**", &principal);
    if (ret)
	krb5_err(context, ret, 1, "krb5_parse_name");

    parse_file(context, principal, 0);
    parse_file(context, principal, 1);

    krb5_free_principal(context, principal);

    krb5_free_context(context);

    return 0;
}
Exemple #16
0
int
main(int argc, char **argv)
{
    krb5_context ctx;
    krb5_get_init_creds_opt *opt;
    char *user, *password, *service = NULL;
    krb5_boolean use_cb;
    krb5_principal client;
    krb5_creds creds;

    if (argc < 4) {
	fprintf(stderr, "Usage: %s username password {1|0} [service]\n",
		argv[0]);
	return 1;
    }
    user = argv[1];
    password = argv[2];
    use_cb = atoi(argv[3]);
    if (argc >= 5)
	service = argv[4];

    assert(krb5_init_context(&ctx) == 0);
    assert(krb5_get_init_creds_opt_alloc(ctx, &opt) == 0);
    if (use_cb) {
	assert(krb5_get_init_creds_opt_set_expire_callback(ctx, opt, expire_cb,
							   &exp_dummy) == 0);
    }
    assert(krb5_parse_name(ctx, user, &client) == 0);
    assert(krb5_get_init_creds_password(ctx, &creds, client, password,
					prompter_cb, &prompt_dummy, 0, service,
					opt) == 0);
    krb5_get_init_creds_opt_free(ctx, opt);
    krb5_free_principal(ctx, client);
    krb5_free_cred_contents(ctx, &creds);
    return 0;
}
Exemple #17
0
int
main(int argc, char **argv)
{
    krb5_error_code ret;
    krb5_context context;
    int ival, val = 0;

    ret = krb5_init_context (&context);
    if (ret)
	errx (1, "krb5_init_context failed: %d", ret);

    val |= ival = string_to_key_test(context);
    if (ival && verbose)
	printf("string to key failed\n");

    val |= ival = krb_enc_test(context);
    if (ival && verbose)
	printf("enc tests failed\n");

    val |= ival = random_to_key(context);
    if (ival && verbose)
	printf("random to key failed\n");

    val |= ival = iov_test(context);
    if (ival && verbose)
	printf("iov test failed\n");

    if (verbose && val == 0)
	printf("all ok\n");
    if (val)
	printf("tests failed\n");

    krb5_free_context(context);

    return val;
}
Exemple #18
0
int
main(int argc, char **argv)
{
    krb5_context context;
    krb5_error_code ret;

    setprogname(argv[0]);

    ret = krb5_init_context(&context);
    if (ret)
	errx (1, "krb5_init_context failed: %d", ret);

    test_fcache_remove(context);
    test_default_name(context);
    test_mcache(context);
    test_init_vs_destroy(context, &krb5_mcc_ops);
    test_init_vs_destroy(context, &krb5_fcc_ops);
    test_mcc_default();
    test_def_cc_name(context);

    krb5_free_context(context);

    return 0;
}
Exemple #19
0
int
main(int argc, char **argv)
{
    krb5_error_code ret;
    krb5_context context;
    krb5_ccache  ccache;
    krb5_principal principal = NULL;
    int optidx = 0;
    krb5_deltat ticket_life = 0;
#ifdef HAVE_SIGACTION
    struct sigaction sa;
#endif

    setprogname(argv[0]);

    setlocale(LC_ALL, "");
    bindtextdomain("heimdal_kuser", HEIMDAL_LOCALEDIR);
    textdomain("heimdal_kuser");

    ret = krb5_init_context(&context);
    if (ret == KRB5_CONFIG_BADFORMAT)
	errx(1, "krb5_init_context failed to parse configuration file");
    else if (ret)
	errx(1, "krb5_init_context failed: %d", ret);

    if (getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
	usage(1);

    if (help_flag)
	usage(0);

    if (version_flag) {
	print_version(NULL);
	exit(0);
    }

    argc -= optidx;
    argv += optidx;

    /*
     * Open the keytab now, we use the keytab to determine the principal's
     * realm when the requested principal has no realm.
     */
    if (use_keytab || keytab_str) {
	if (keytab_str)
	    ret = krb5_kt_resolve(context, keytab_str, &kt);
	else
	    ret = krb5_kt_default(context, &kt);
	if (ret)
	    krb5_err(context, 1, ret, "resolving keytab");
    }

    if (pk_enterprise_flag) {
	ret = krb5_pk_enterprise_cert(context, pk_user_id,
				      argv[0], &principal,
				      &ent_user_id);
	if (ret)
	    krb5_err(context, 1, ret, "krb5_pk_enterprise_certs");

	pk_user_id = NULL;

    } else if (anonymous_flag) {

	ret = krb5_make_principal(context, &principal, argv[0],
				  KRB5_WELLKNOWN_NAME, KRB5_ANON_NAME,
				  NULL);
	if (ret)
	    krb5_err(context, 1, ret, "krb5_make_principal");
	krb5_principal_set_type(context, principal, KRB5_NT_WELLKNOWN);

    } else if (use_keytab || keytab_str) {
	get_princ_kt(context, &principal, argv[0]);
    } else {
	get_princ(context, &principal, argv[0]);
    }

    if (fcache_version)
	krb5_set_fcache_version(context, fcache_version);

    if (renewable_flag == -1)
	/* this seems somewhat pointless, but whatever */
	krb5_appdefault_boolean(context, "kinit",
				krb5_principal_get_realm(context, principal),
				"renewable", FALSE, &renewable_flag);
    if (do_afslog == -1)
	krb5_appdefault_boolean(context, "kinit",
				krb5_principal_get_realm(context, principal),
				"afslog", TRUE, &do_afslog);

    if (cred_cache)
	ret = krb5_cc_resolve(context, cred_cache, &ccache);
    else {
	if (argc > 1) {
	    char s[1024];
	    ret = krb5_cc_new_unique(context, NULL, NULL, &ccache);
	    if (ret)
		krb5_err(context, 1, ret, "creating cred cache");
	    snprintf(s, sizeof(s), "%s:%s",
		     krb5_cc_get_type(context, ccache),
		     krb5_cc_get_name(context, ccache));
	    setenv("KRB5CCNAME", s, 1);
	} else {
	    ret = krb5_cc_cache_match(context, principal, &ccache);
	    if (ret) {
		const char *type;
		ret = krb5_cc_default(context, &ccache);
		if (ret)
		    krb5_err(context, 1, ret,
			     N_("resolving credentials cache", ""));

		/*
		 * Check if the type support switching, and we do,
		 * then do that instead over overwriting the current
		 * default credential
		 */
		type = krb5_cc_get_type(context, ccache);
		if (krb5_cc_support_switch(context, type)) {
		    krb5_cc_close(context, ccache);
		    ret = get_switched_ccache(context, type, principal,
					      &ccache);
		}
	    }
	}
    }
    if (ret)
	krb5_err(context, 1, ret, N_("resolving credentials cache", ""));

#ifndef NO_AFS
    if (argc > 1 && k_hasafs())
	k_setpag();
#endif

    if (lifetime) {
	int tmp = parse_time(lifetime, "s");
	if (tmp < 0)
	    errx(1, N_("unparsable time: %s", ""), lifetime);

	ticket_life = tmp;
    }

    if (addrs_flag == 0 && extra_addresses.num_strings > 0)
	krb5_errx(context, 1,
		  N_("specifying both extra addresses and "
		     "no addresses makes no sense", ""));
    {
	int i;
	krb5_addresses addresses;
	memset(&addresses, 0, sizeof(addresses));
	for(i = 0; i < extra_addresses.num_strings; i++) {
	    ret = krb5_parse_address(context, extra_addresses.strings[i],
				     &addresses);
	    if (ret == 0) {
		krb5_add_extra_addresses(context, &addresses);
		krb5_free_addresses(context, &addresses);
	    }
	}
	free_getarg_strings(&extra_addresses);
    }

    if (renew_flag || validate_flag) {
	ret = renew_validate(context, renew_flag, validate_flag,
			     ccache, server_str, ticket_life);

#ifndef NO_AFS
	if (ret == 0 && server_str == NULL && do_afslog && k_hasafs())
	    krb5_afslog(context, ccache, NULL, NULL);
#endif

	exit(ret != 0);
    }

    ret = get_new_tickets(context, principal, ccache, ticket_life, 1);
    if (ret)
	exit(1);

#ifndef NO_AFS
    if (ret == 0 && server_str == NULL && do_afslog && k_hasafs())
	krb5_afslog(context, ccache, NULL, NULL);
#endif

    if (argc > 1) {
	struct renew_ctx ctx;
	time_t timeout;

	timeout = ticket_lifetime(context, ccache, principal,
				  server_str, NULL) / 2;

	ctx.context = context;
	ctx.ccache = ccache;
	ctx.principal = principal;
	ctx.ticket_life = ticket_life;
	ctx.timeout = timeout;

#ifdef HAVE_SIGACTION
	memset(&sa, 0, sizeof(sa));
	sigemptyset(&sa.sa_mask);
	sa.sa_handler = handle_siginfo;

	sigaction(SIGINFO, &sa, NULL);
#endif

	ret = simple_execvp_timed(argv[1], argv+1,
				  renew_func, &ctx, timeout);
#define EX_NOEXEC	126
#define EX_NOTFOUND	127
	if (ret == EX_NOEXEC)
	    krb5_warnx(context, N_("permission denied: %s", ""), argv[1]);
	else if (ret == EX_NOTFOUND)
	    krb5_warnx(context, N_("command not found: %s", ""), argv[1]);

	krb5_cc_destroy(context, ccache);
#ifndef NO_AFS
	if (k_hasafs())
	    k_unlog();
#endif
    } else {
	krb5_cc_close(context, ccache);
	ret = 0;
    }
    krb5_free_principal(context, principal);
    if (kt)
	krb5_kt_close(context, kt);
    krb5_free_context(context);
    return ret;
}
Exemple #20
0
/*
 * Get a ticket granting ticket and stuff it in the cache
 */
static const char *
get_tgt(
    char *	keytab_name,
    char *	principal_name)
{
    krb5_context context;
    krb5_error_code ret;
    krb5_principal client = NULL, server = NULL;
    krb5_creds creds;
    krb5_keytab keytab;
    krb5_ccache ccache;
    krb5_timestamp now;
#ifdef KRB5_HEIMDAL_INCLUDES
    krb5_data tgtname = { KRB5_TGS_NAME_SIZE, KRB5_TGS_NAME };
#else
    krb5_data tgtname = { 0, KRB5_TGS_NAME_SIZE, KRB5_TGS_NAME };
#endif
    static char *error = NULL;

    if (error != NULL) {
	amfree(error);
	error = NULL;
    }
    if ((ret = krb5_init_context(&context)) != 0) {
	error = vstrallocf(_("error initializing krb5 context: %s"),
	    error_message(ret));
	return (error);
    }

    /*krb5_init_ets(context);*/

    if(!keytab_name) {
        error = vstrallocf(_("error  -- no krb5 keytab defined"));
        return(error);
    }

    if(!principal_name) {
        error = vstrallocf(_("error  -- no krb5 principal defined"));
        return(error);
    }

    /*
     * Resolve keytab file into a keytab object
     */
    if ((ret = krb5_kt_resolve(context, keytab_name, &keytab)) != 0) {
	error = vstrallocf(_("error resolving keytab %s: %s"), keytab_name, 
	    error_message(ret));
	return (error);
    }

    /*
     * Resolve the amanda service held in the keytab into a principal
     * object
     */
    ret = krb5_parse_name(context, principal_name, &client);
    if (ret != 0) {
	error = vstrallocf(_("error parsing %s: %s"), principal_name,
	    error_message(ret));
	return (error);
    }

#ifdef KRB5_HEIMDAL_INCLUDES
    ret = krb5_build_principal_ext(context, &server,
        krb5_realm_length(*krb5_princ_realm(context, client)),
        krb5_realm_data(*krb5_princ_realm(context, client)),
        tgtname.length, tgtname.data,
        krb5_realm_length(*krb5_princ_realm(context, client)),
        krb5_realm_data(*krb5_princ_realm(context, client)),
        0);
#else
    ret = krb5_build_principal_ext(context, &server,
	krb5_princ_realm(context, client)->length,
	krb5_princ_realm(context, client)->data,
	tgtname.length, tgtname.data,
	krb5_princ_realm(context, client)->length,
	krb5_princ_realm(context, client)->data,
	0);
#endif
    if (ret != 0) {
	error = vstrallocf(_("error while building server name: %s"),
	    error_message(ret));
	return (error);
    }

    ret = krb5_timeofday(context, &now);
    if (ret != 0) {
	error = vstrallocf(_("error getting time of day: %s"), error_message(ret));
	return (error);
    }

    memset(&creds, 0, SIZEOF(creds));
    creds.times.starttime = 0;
    creds.times.endtime = now + AMANDA_TKT_LIFETIME;

    creds.client = client;
    creds.server = server;

    /*
     * Get a ticket for the service, using the keytab
     */
    ret = krb5_get_in_tkt_with_keytab(context, 0, NULL, NULL, NULL,
	keytab, 0, &creds, 0);

    if (ret != 0) {
	error = vstrallocf(_("error getting ticket for %s: %s"),
	    principal_name, error_message(ret));
	goto cleanup2;
    }

    if ((ret = krb5_cc_default(context, &ccache)) != 0) {
	error = vstrallocf(_("error initializing ccache: %s"), error_message(ret));
	goto cleanup;
    }
    if ((ret = krb5_cc_initialize(context, ccache, client)) != 0) {
	error = vstrallocf(_("error initializing ccache: %s"), error_message(ret));
	goto cleanup;
    }
    if ((ret = krb5_cc_store_cred(context, ccache, &creds)) != 0) {
	error = vstrallocf(_("error storing creds in ccache: %s"), 
	    error_message(ret));
	/* FALLTHROUGH */
    }
    krb5_cc_close(context, ccache);
cleanup:
    krb5_free_cred_contents(context, &creds);
cleanup2:
#if 0
    krb5_free_principal(context, client);
    krb5_free_principal(context, server);
#endif
    krb5_free_context(context);
    return (error);
}
Exemple #21
0
int
main(int argc, char **argv)
{
    krb5_error_code ret;
    char **files;
    int optidx = 0;
    int i;
    krb5_log_facility *logfacility;
    krb5_keytab keytab;
    krb5_socket_t sfd = rk_INVALID_SOCKET;

    setprogname(argv[0]);

    ret = krb5_init_context(&context);
    if (ret)
	errx (1, "krb5_init_context failed: %d", ret);

    if (getarg(args, num_args, argc, argv, &optidx)) {
	warnx("error at argument `%s'", argv[optidx]);
	usage(1);
    }

    if (help_flag)
	usage (0);

    if (version_flag) {
	print_version(NULL);
	exit(0);
    }

    argc -= optidx;
    argv += optidx;

    if (config_file == NULL) {
	asprintf(&config_file, "%s/kdc.conf", hdb_db_dir(context));
	if (config_file == NULL)
	    errx(1, "out of memory");
    }

    ret = krb5_prepend_config_files_default(config_file, &files);
    if (ret)
	krb5_err(context, 1, ret, "getting configuration files");

    ret = krb5_set_config_files(context, files);
    krb5_free_config_files(files);
    if(ret)
	krb5_err(context, 1, ret, "reading configuration files");

    ret = krb5_openlog(context, "kadmind", &logfacility);
    if (ret)
	krb5_err(context, 1, ret, "krb5_openlog");
    ret = krb5_set_warn_dest(context, logfacility);
    if (ret)
	krb5_err(context, 1, ret, "krb5_set_warn_dest");

    ret = krb5_kt_register(context, &hdb_kt_ops);
    if(ret)
	krb5_err(context, 1, ret, "krb5_kt_register");

    ret = krb5_kt_resolve(context, keytab_str, &keytab);
    if(ret)
	krb5_err(context, 1, ret, "krb5_kt_resolve");

    kadm5_setup_passwd_quality_check (context, check_library, check_function);

    for (i = 0; i < policy_libraries.num_strings; i++) {
	ret = kadm5_add_passwd_quality_verifier(context,
						policy_libraries.strings[i]);
	if (ret)
	    krb5_err(context, 1, ret, "kadm5_add_passwd_quality_verifier");
    }
    ret = kadm5_add_passwd_quality_verifier(context, NULL);
    if (ret)
	krb5_err(context, 1, ret, "kadm5_add_passwd_quality_verifier");

    if(debug_flag) {
	int debug_port;
	
	if(port_str == NULL)
	    debug_port = krb5_getportbyname (context, "kerberos-adm",
					     "tcp", 749);
	else
	    debug_port = htons(atoi(port_str));
	mini_inetd(debug_port, &sfd);
    } else {
#ifdef _WIN32
	pidfile(NULL);
	start_server(context, port_str);
#else
	struct sockaddr_storage __ss;
	struct sockaddr *sa = (struct sockaddr *)&__ss;
	socklen_t sa_size = sizeof(__ss);

	/*
	 * Check if we are running inside inetd or not, if not, start
	 * our own server.
	 */

	if(roken_getsockname(STDIN_FILENO, sa, &sa_size) < 0 &&
	   rk_SOCK_ERRNO == ENOTSOCK) {
	    pidfile(NULL);
	    start_server(context, port_str);
	}
#endif /* _WIN32 */
	sfd = STDIN_FILENO;
    }

    if(realm)
	krb5_set_default_realm(context, realm); /* XXX */

    kadmind_loop(context, keytab, sfd);

    return 0;
}
Exemple #22
0
int
_GetSecurityObject(struct afscp_cell *cell)
{
    int code = ENOENT;
#ifdef HAVE_KERBEROS
    krb5_context context;
    krb5_creds match;
    krb5_creds *cred;
    krb5_ccache cc;
    char **realms, *realm;
    struct afsconf_cell celldata;
    char localcell[MAXCELLCHARS + 1];
    struct rx_securityClass *sc;
    struct ktc_encryptionKey k;
    int i;
    rxkad_level l;
    code = _GetCellInfo(cell->name, &celldata);
    if (code != 0) {
	goto try_anon;
    }

    if (authas_name[0]) {
	code = _GetLocalSecurityObject(cell, authas_name, authas_inst);
	if (code == 0) {
	    return 0;
	}
    }

    code = krb5_init_context(&context);	/* see aklog.c main() */
    if (code != 0) {
	goto try_anon;
    }

    if (cell->realm == NULL) {
	realm = NULL;
	code = krb5_get_host_realm(context, celldata.hostName[0], &realms);

	if (code == 0) {
	    strlcpy(localcell, realms[0], sizeof(localcell));
	    krb5_free_host_realm(context, realms);
	    realm = localcell;
	} else
	    goto try_anon;
    } else {
	realm = cell->realm;
	strlcpy(localcell, realm, MAXCELLCHARS + 1);
    }
    if (realm)
	if (realm == NULL) {
	    for (i = 0; (i < MAXCELLCHARS && cell->name[i]); i++) {
		if (isalpha(cell->name[i]))
		    localcell[i] = toupper(cell->name[i]);
		else
		    localcell[i] = cell->name[i];
	    }
	    localcell[i] = '\0';
	    realm = localcell;
	}
    cc = NULL;
    code = krb5_cc_default(context, &cc);

    memset(&match, 0, sizeof(match));
    Z_enctype(Z_credskey(&match)) = ENCTYPE_DES_CBC_CRC;

    if (code == 0)
	code = krb5_cc_get_principal(context, cc, &match.client);
    if (code == 0)
	code = krb5_build_principal(context, &match.server,
				    strlen(realm), realm,
				    "afs", cell->name, NULL);

    if (code != 0) {
	krb5_free_cred_contents(context, &match);
	if (cc)
	    krb5_cc_close(context, cc);
	krb5_free_context(context);
	goto try_anon;
    }

    code = krb5_get_credentials(context, 0, cc, &match, &cred);
    if (code != 0) {
	krb5_free_principal(context, match.server);
	match.server = NULL;

	code = krb5_build_principal(context, &match.server,
				    strlen(realm), realm, "afs", NULL);
	if (code == 0)
	    code = krb5_get_credentials(context, 0, cc, &match, &cred);
	if (code != 0) {
	    krb5_free_cred_contents(context, &match);
	    if (cc)
		krb5_cc_close(context, cc);
	    krb5_free_context(context);
	    goto try_anon;
	}
    }

    if (insecure)
	l = rxkad_clear;
    else
	l = rxkad_crypt;
    memcpy(&k.data, Z_keydata(Z_credskey(cred)), 8);
    sc = (struct rx_securityClass *)rxkad_NewClientSecurityObject
	(l, &k, RXKAD_TKT_TYPE_KERBEROS_V5,
	 cred->ticket.length, cred->ticket.data);
    krb5_free_creds(context, cred);
    krb5_free_cred_contents(context, &match);
    if (cc)
	krb5_cc_close(context, cc);
    krb5_free_context(context);
    cell->security = sc;
    cell->scindex = 2;
    return 0;

    try_anon:
#endif /* HAVE_KERBEROS */
    if (try_anonymous)
	return _GetNullSecurityObject(cell);
    else
	return code;
}
Exemple #23
0
krb5_error_code kdc_set_password(krb5_context context, krb5_ccache ccache,
                                 char *newpw, char *user, char *domain,
                                 int *result_code, char *admin_server)
{
  krb5_data         chpw_snd;
  krb5_data         chpw_rcv;
  krb5_data         result_string;
  krb5_data         result_code_string;
  krb5_address      local_kaddr;
  krb5_address      remote_kaddr;
  char              userrealm[256];
  char              temp[256];
  krb5_error_code   code;
  struct sockaddr   local_addr;
  struct sockaddr   remote_addr;
  int               i;
  int               addrlen;
  int               cc;
  int               local_result_code;
  int               nfds;
  krb5_principal    targprinc;
  struct timeval    TimeVal;
  fd_set            readfds;
  krb5_creds        *credsp = NULL;
  struct hostent    *hp;
  SOCKET            kdc_socket;
  struct sockaddr_in  kdc_server;
  krb5_auth_context   auth_context = NULL;
  krb5_creds          creds;
  krb5_data           ap_req;
  char                *code_string;

  memset(&local_addr, 0, sizeof(local_addr));
  memset(&local_kaddr, 0, sizeof(local_kaddr));
  memset(&result_string, 0, sizeof(result_string));
  memset(&remote_kaddr, 0, sizeof(remote_kaddr));
  memset(&chpw_snd, 0, sizeof(krb5_data));
  memset(&chpw_rcv, 0, sizeof(krb5_data));
  memset(userrealm, '\0', sizeof(userrealm));
  targprinc = NULL;

  chpw_rcv.length = 1500;
  chpw_rcv.data = (char *) malloc(chpw_rcv.length);

  for (i = 0; i < (int)strlen(domain); i++)
    userrealm[i] = toupper(domain[i]);

  sprintf(temp, "%s@%s", user, userrealm);
  krb5_parse_name(context, temp, &targprinc);
  
  if (credsp == NULL)
    {
      memset(&creds, 0, sizeof(creds));
      memset(&ap_req, 0, sizeof(krb5_data));
      memset(&result_string, 0, sizeof(krb5_data));
      memset(&result_code_string, 0, sizeof(krb5_data));
      sprintf(temp, "%s@%s", "kadmin/changepw", userrealm);

      if(code = krb5_init_context(&context)) 
	goto cleanup;
      
      if(code = krb5_cc_default(context, &ccache)) 
	goto cleanup;

      if (krb5_parse_name(context, temp, &creds.server))
	goto cleanup;

      if (krb5_cc_get_principal(context, ccache, &creds.client))
	goto cleanup;

      if (krb5_get_credentials(context, 0, ccache, &creds, &credsp))
	goto cleanup;
    }

  if ((code = krb5_change_set_password(context, credsp, newpw,
				       targprinc, &result_code,
				       &result_code_string,
				       &result_string))) {

    goto cleanup;
  }


cleanup:
  if (targprinc != NULL)
    krb5_free_principal(context, targprinc);
  return(code);
}
Exemple #24
0
int main(int argc, const char *argv[])
{
	static const char *server = NULL;
	static const char *principal = NULL;
	static const char *keytab = NULL;
	static const char *enctypes_string = NULL;
	static const char *binddn = NULL;
	static const char *bindpw = NULL;
	char *ldap_uri = NULL;
	static const char *sasl_mech = NULL;
	static const char *ca_cert_file = NULL;
	int quiet = 0;
	int askpass = 0;
	int permitted_enctypes = 0;
	int retrieve = 0;
        struct poptOption options[] = {
            { "quiet", 'q', POPT_ARG_NONE, &quiet, 0,
              _("Print as little as possible"), _("Output only on errors")},
            { "server", 's', POPT_ARG_STRING, &server, 0,
              _("Contact this specific KDC Server"),
              _("Server Name") },
            { "principal", 'p', POPT_ARG_STRING, &principal, 0,
              _("The principal to get a keytab for (ex: ftp/[email protected])"),
              _("Kerberos Service Principal Name") },
            { "keytab", 'k', POPT_ARG_STRING, &keytab, 0,
              _("The keytab file to append the new key to (will be "
                "created if it does not exist)."),
              _("Keytab File Name") },
	    { "enctypes", 'e', POPT_ARG_STRING, &enctypes_string, 0,
              _("Encryption types to request"),
              _("Comma separated encryption types list") },
	    { "permitted-enctypes", 0, POPT_ARG_NONE, &permitted_enctypes, 0,
              _("Show the list of permitted encryption types and exit"),
              _("Permitted Encryption Types") },
	    { "password", 'P', POPT_ARG_NONE, &askpass, 0,
              _("Asks for a non-random password to use for the principal"), NULL },
	    { "binddn", 'D', POPT_ARG_STRING, &binddn, 0,
              _("LDAP DN"), _("DN to bind as if not using kerberos") },
	    { "bindpw", 'w', POPT_ARG_STRING, &bindpw, 0,
              _("LDAP password"), _("password to use if not using kerberos") },
	    { "cacert", 0, POPT_ARG_STRING, &ca_cert_file, 0,
              _("Path to the IPA CA certificate"), _("IPA CA certificate")},
	    { "ldapuri", 'H', POPT_ARG_STRING, &ldap_uri, 0,
              _("LDAP uri to connect to. Mutually exclusive with --server"),
              _("url")},
	    { "mech", 'Y', POPT_ARG_STRING, &sasl_mech, 0,
              _("LDAP SASL bind mechanism if no bindd/bindpw"),
              _("GSSAPI|EXTERNAL") },
	    { "retrieve", 'r', POPT_ARG_NONE, &retrieve, 0,
              _("Retrieve current keys without changing them"), NULL },
            POPT_AUTOHELP
            POPT_TABLEEND
	};
	poptContext pc;
	char *ktname;
	char *password = NULL;
	krb5_context krbctx;
	krb5_ccache ccache;
	krb5_principal uprinc = NULL;
	krb5_principal sprinc;
	krb5_error_code krberr;
	struct keys_container keys = { 0 };
	krb5_keytab kt;
	int kvno;
	int i, ret;
	char *err_msg;

    ret = init_gettext();
    if (ret) {
        fprintf(stderr, "Failed to load translations\n");
    }

	krberr = krb5_init_context(&krbctx);
	if (krberr) {
		fprintf(stderr, _("Kerberos context initialization failed\n"));
		exit(1);
	}

	pc = poptGetContext("ipa-getkeytab", argc, (const char **)argv, options, 0);
	ret = poptGetNextOpt(pc);
	if (ret == -1 && permitted_enctypes &&
	    !(server || principal || keytab || quiet)) {
		krb5_enctype *ktypes;
		char enc[79]; /* fit std terminal or truncate */

		krberr = krb5_get_permitted_enctypes(krbctx, &ktypes);
		if (krberr) {
			fprintf(stderr, _("No system preferred enctypes ?!\n"));
			exit(1);
		}
		fprintf(stdout, _("Supported encryption types:\n"));
		for (i = 0; ktypes[i]; i++) {
			krberr = krb5_enctype_to_string(ktypes[i], enc, 79);
			if (krberr) {
				fprintf(stderr, _("Warning: "
                                        "failed to convert type (#%d)\n"), i);
				continue;
			}
			fprintf(stdout, "%s\n", enc);
		}
		ipa_krb5_free_ktypes(krbctx, ktypes);
		exit (0);
	}

	if (ret != -1 || !principal || !keytab || permitted_enctypes) {
		if (!quiet) {
			poptPrintUsage(pc, stderr, 0);
		}
		exit(2);
	}

	if (NULL!=binddn && NULL==bindpw) {
		fprintf(stderr,
                        _("Bind password required when using a bind DN.\n"));
		if (!quiet)
			poptPrintUsage(pc, stderr, 0);
		exit(10);
	}

    if (NULL != binddn && NULL != sasl_mech) {
        fprintf(stderr, _("Cannot specify both SASL mechanism "
                          "and bind DN simultaneously.\n"));
        if (!quiet)
            poptPrintUsage(pc, stderr, 0);
        exit(2);
    }

    if (sasl_mech && check_sasl_mech(sasl_mech)) {
        fprintf(stderr, _("Invalid SASL bind mechanism\n"));
        if (!quiet)
            poptPrintUsage(pc, stderr, 0);
        exit(2);
    }

    if (!binddn && !sasl_mech) {
        sasl_mech = LDAP_SASL_GSSAPI;
    }

    if (server && ldap_uri) {
        fprintf(stderr, _("Cannot specify server and LDAP uri "
                          "simultaneously.\n"));
        if (!quiet)
            poptPrintUsage(pc, stderr, 0);
        exit(2);
    }

    if (!server && !ldap_uri) {
        struct ipa_config *ipacfg = NULL;

        ret = read_ipa_config(&ipacfg);
        if (ret == 0) {
            server = ipacfg->server_name;
            ipacfg->server_name = NULL;
        }
        free(ipacfg);
        if (!server) {
            fprintf(stderr, _("Server name not provided and unavailable\n"));
            exit(2);
        }
    }
    if (server) {
        ret = ipa_server_to_uri(server, sasl_mech, &ldap_uri);
        if (ret) {
            exit(ret);
        }
    }

    if (!ca_cert_file) {
        ca_cert_file = DEFAULT_CA_CERT_FILE;
    }

    if (askpass && retrieve) {
        fprintf(stderr, _("Incompatible options provided (-r and -P)\n"));
        exit(2);
    }

        if (askpass) {
		password = ask_password(krbctx);
		if (!password) {
			exit(2);
		}
	} else if (enctypes_string && strchr(enctypes_string, ':')) {
		if (!quiet) {
			fprintf(stderr, _("Warning: salt types are not honored"
                                " with randomized passwords (see opt. -P)\n"));
		}
	}

	ret = asprintf(&ktname, "WRFILE:%s", keytab);
	if (ret == -1) {
		exit(3);
	}

	krberr = krb5_parse_name(krbctx, principal, &sprinc);
	if (krberr) {
		fprintf(stderr, _("Invalid Service Principal Name\n"));
		exit(4);
	}

	if (NULL == bindpw && strcmp(sasl_mech, LDAP_SASL_GSSAPI) == 0) {
		krberr = krb5_cc_default(krbctx, &ccache);
		if (krberr) {
			fprintf(stderr,
                                _("Kerberos Credential Cache not found. "
				  "Do you have a Kerberos Ticket?\n"));
			exit(5);
		}

		krberr = krb5_cc_get_principal(krbctx, ccache, &uprinc);
		if (krberr) {
			fprintf(stderr,
                                _("Kerberos User Principal not found. "
				  "Do you have a valid Credential Cache?\n"));
			exit(6);
		}
	}

	krberr = krb5_kt_resolve(krbctx, ktname, &kt);
	if (krberr) {
		fprintf(stderr, _("Failed to open Keytab\n"));
		exit(7);
	}

    kvno = -1;
    ret = ldap_get_keytab(krbctx, (retrieve == 0), password, enctypes_string,
                          ldap_uri, principal, uprinc, binddn, bindpw,
                          sasl_mech, ca_cert_file,
                          &keys, &kvno, &err_msg);
    if (ret) {
        if (!quiet && err_msg != NULL) {
            fprintf(stderr, "%s", err_msg);
        }
    }

    if (retrieve == 0 && kvno == -1) {
        if (!quiet) {
            fprintf(stderr,
                    _("Retrying with pre-4.0 keytab retrieval method...\n"));
        }

        /* create key material */
        ret = create_keys(krbctx, sprinc, password, enctypes_string, &keys, &err_msg);
        if (!ret) {
            if (err_msg != NULL) {
                fprintf(stderr, "%s", err_msg);
            }

            fprintf(stderr, _("Failed to create key material\n"));
            exit(8);
        }

        kvno = ldap_set_keytab(krbctx, ldap_uri, principal, uprinc, binddn,
                               bindpw, sasl_mech, ca_cert_file, &keys);
    }

    if (kvno == -1) {
        fprintf(stderr, _("Failed to get keytab\n"));
        exit(9);
    }

	for (i = 0; i < keys.nkeys; i++) {
		krb5_keytab_entry kt_entry;
		memset((char *)&kt_entry, 0, sizeof(kt_entry));
		kt_entry.principal = sprinc;
		kt_entry.key = keys.ksdata[i].key;
		kt_entry.vno = kvno;

		krberr = krb5_kt_add_entry(krbctx, kt, &kt_entry);
		if (krberr) {
			fprintf(stderr,
                                _("Failed to add key to the keytab\n"));
			exit (11);
		}
	}

	free_keys_contents(krbctx, &keys);

	krberr = krb5_kt_close(krbctx, kt);
	if (krberr) {
		fprintf(stderr, _("Failed to close the keytab\n"));
		exit (12);
	}

	if (!quiet) {
		fprintf(stderr,
			_("Keytab successfully retrieved and stored in: %s\n"),
			keytab);
	}
	exit(0);
}
Exemple #25
0
static int
get_user_ccache(const ntlm_name name, char **domainp, char **usernamep, struct ntlm_buf *key)
{
    krb5_context context = NULL;
    krb5_principal client;
    krb5_ccache id = NULL;
    krb5_error_code ret;
    char *confname;
    krb5_data data;
    int aret;

    *domainp = NULL;
    *usernamep = NULL;
    krb5_data_zero(&data);
    key->length = 0;
    key->data = NULL;

    ret = krb5_init_context(&context);
    if (ret)
	return ret;

    ret = krb5_cc_default(context, &id);
    if (ret)
	goto out;

    ret = krb5_cc_get_principal(context, id, &client);
    if (ret)
	goto out;

    ret = krb5_unparse_name_flags(context, client,
				  KRB5_PRINCIPAL_UNPARSE_NO_REALM,
				  usernamep);
    krb5_free_principal(context, client);
    if (ret)
	goto out;

    if (name != NULL) {
        *domainp = strdup(name->domain);
    } else {
        krb5_data data_domain;

        krb5_data_zero(&data_domain);
        ret = krb5_cc_get_config(context, id, NULL, "default-ntlm-domain",
                                 &data_domain);
        if (ret)
            goto out;

        *domainp = strndup(data_domain.data, data_domain.length);
        krb5_data_free(&data_domain);
    }

    if (*domainp == NULL) {
        ret = krb5_enomem(context);
	goto out;
    }

    aret = asprintf(&confname, "ntlm-key-%s", *domainp);
    if (aret == -1) {
        ret = krb5_enomem(context);
	goto out;
    }

    ret = krb5_cc_get_config(context, id, NULL, confname, &data);
    if (ret)
        goto out;

    key->data = malloc(data.length);
    if (key->data == NULL) {
	ret = ENOMEM;
	goto out;
    }
    key->length = data.length;
    memcpy(key->data, data.data, data.length);

 out:
    krb5_data_free(&data);
    if (id)
	krb5_cc_close(context, id);

    krb5_free_context(context);

    return ret;
}
Exemple #26
0
int
main(int argc, char **argv)
{
	int			c;
	bool_t			verbose = FALSE;
	bool_t			headeronly = FALSE;
	uint32_t		entry = 0;
	krb5_context		context;
	kadm5_config_params	params;
	kdb_log_context		*log_ctx;
	kdb_hlog_t		*ulog = NULL;

	(void) setlocale(LC_ALL, "");

#if !defined(TEXT_DOMAIN)
#define	TEXT_DOMAIN "SYS_TEST"
#endif /* TEXT_DOMAIN */

	(void) textdomain(TEXT_DOMAIN);

	if (geteuid() != (uid_t)0) {
		(void) fprintf(stderr,
		    gettext("kproplog must be run as root\n\n"));
		exit(1);
	}

	progname = argv[0];

	while ((c = getopt(argc, argv, "vhe:")) != -1) {
		switch (c) {
			case 'h':
				headeronly = TRUE;
				break;
			case 'e':
				entry = atoi(optarg);
				break;
			case 'v':
				verbose = TRUE;
				break;
			default:
				usage();
		}
	}

	if (krb5_init_context(&context)) {
		(void) fprintf(stderr,
		    gettext("Unable to initialize Kerberos\n\n"));
		exit(1);
	}

	(void) memset((char *)&params, 0, sizeof (params));

	if (kadm5_get_config_params(context, NULL, NULL, &params, &params)) {
		(void) fprintf(stderr,
		    gettext("Couldn't read database_name\n\n"));
		exit(1);
	}

	(void) printf(gettext("\nKerberos update log (%s.ulog)\n"),
	    params.dbname);

	if (ulog_map(context, &params, FKPROPLOG)) {
		(void) fprintf(stderr, gettext("Unable to map log file "
		    "%s.ulog\n\n"), params.dbname);
		exit(1);
	}

	log_ctx = context->kdblog_context;
	if (log_ctx)
		ulog = log_ctx->ulog;
	else {
		(void) fprintf(stderr, gettext("Unable to map log file "
		    "%s.ulog\n\n"), params.dbname);
		exit(1);
	}

	if (ulog->kdb_hmagic != KDB_HMAGIC) {
		(void) fprintf(stderr,
		    gettext("Corrupt header log, exiting\n\n"));
		exit(1);
	}

	(void) printf(gettext("Update log dump :\n"));
	(void) printf(gettext("\tLog version # : %u\n"), ulog->db_version_num);
	(void) printf(gettext("\tLog state : "));
	switch (ulog->kdb_state) {
		case KDB_STABLE:
			(void) printf(gettext("Stable\n"));
			break;
		case KDB_UNSTABLE:
			(void) printf(gettext("Unstable\n"));
			break;
		case KDB_CORRUPT:
			(void) printf(gettext("Corrupt\n"));
			break;
		default:
			(void) printf(gettext("Unknown state: %d\n"),
			    ulog->kdb_state);
			break;
	}
	(void) printf(gettext("\tEntry block size : %u\n"), ulog->kdb_block);
	(void) printf(gettext("\tNumber of entries : %u\n"), ulog->kdb_num);

	if (ulog->kdb_last_sno == 0)
		(void) printf(gettext("\tLast serial # : None\n"));
	else {
		if (ulog->kdb_first_sno == 0)
			(void) printf(gettext("\tFirst serial # : None\n"));
		else {
			(void) printf(gettext("\tFirst serial # : "));
			(void) printf("%u\n", ulog->kdb_first_sno);
		}

		(void) printf(gettext("\tLast serial # : "));
		(void) printf("%u\n", ulog->kdb_last_sno);
	}

	if (ulog->kdb_last_time.seconds == 0L) {
		(void) printf(gettext("\tLast time stamp : None\n"));
	} else {
		if (ulog->kdb_first_time.seconds == 0L)
			(void) printf(gettext("\tFirst time stamp : None\n"));
		else {
			(void) printf(gettext("\tFirst time stamp : %s"),
			    ctime((time_t *)
			    &(ulog->kdb_first_time.seconds)));
		}

		(void) printf(gettext("\tLast time stamp : %s\n"),
		    ctime((time_t *)&(ulog->kdb_last_time.seconds)));
	}

	if ((!headeronly) && ulog->kdb_num) {
		print_update(ulog, entry, verbose);
	}

	(void) printf("\n");

	return (0);
}
int
krb5_login(char *username, char *invokinguser, char *password, int login,
    int tickets)
{
	int return_code = AUTH_FAILED;

	if (username == NULL || password == NULL)
		return (AUTH_FAILED);

	if (strcmp(__progname, "krb5-or-pwd") == 0 &&
	    strcmp(username,"root") == 0 && invokinguser[0] == '\0')
		return (AUTH_FAILED);

	ret = krb5_init_context(&context);
	if (ret != 0) {
		krb5_syslog(context, LOG_ERR, ret, "krb5_init_context");
		exit(1);
	}

	ret = krb5_cc_gen_new(context, &krb5_mcc_ops, &ccache);
	if (ret != 0) {
		krb5_syslog(context, LOG_ERR, ret, "krb5_cc_gen_new");
		exit(1);
	}

	if (strcmp(username, "root") == 0 && invokinguser[0] != '\0') {
		char *tmp;

		ret = asprintf(&tmp, "%s/root", invokinguser);
		if (ret == -1) {
			krb5_syslog(context, LOG_ERR, ret, "asprintf");
			exit(1);
		}
		ret = krb5_parse_name(context, tmp, &princ);
		free(tmp);
	} else
		ret = krb5_parse_name(context, username, &princ);
	if (ret != 0) {
		krb5_syslog(context, LOG_ERR, ret, "krb5_parse_name");
		exit(1);
	}

	ret = krb5_verify_user_lrealm(context, princ, ccache,
	    password, 1, NULL);

	switch (ret) {
	case 0: {
		struct passwd *pwd;

		pwd = getpwnam(username);
		if (pwd == NULL) {
			krb5_syslog(context, LOG_ERR, ret,
			    "%s: no such user", username);
			return (AUTH_FAILED);
		}
		fprintf(back, BI_AUTH "\n");
		store_tickets(pwd, login && tickets, login && tickets, login);
		return_code = AUTH_OK;
		break;
	}
	case KRB5KRB_AP_ERR_MODIFIED:
		/* XXX syslog here? */
	case KRB5KRB_AP_ERR_BAD_INTEGRITY:
		break;
	default:
		krb5_syslog(context, LOG_ERR, ret, "verify");
		break;
	}

	krb5_free_context(context);
	krb5_free_principal(context, princ);
	krb5_cc_close(context, ccache);

	return (return_code);
}
Exemple #28
0
static int
proto (int sock, const char *hostname, const char *service)
{
    struct sockaddr_in remote, local;
    socklen_t addrlen;
    krb5_address remote_addr, local_addr;
    krb5_context context;
    krb5_ccache ccache;
    krb5_auth_context auth_context;
    krb5_error_code status;
    krb5_principal client;
    krb5_data data;
    krb5_data packet;
    krb5_creds mcred, cred;
    krb5_ticket *ticket;

    addrlen = sizeof(local);
    if (getsockname (sock, (struct sockaddr *)&local, &addrlen) < 0
	|| addrlen != sizeof(local))
	err (1, "getsockname(%s)", hostname);

    addrlen = sizeof(remote);
    if (getpeername (sock, (struct sockaddr *)&remote, &addrlen) < 0
	|| addrlen != sizeof(remote))
	err (1, "getpeername(%s)", hostname);

    status = krb5_init_context(&context);
    if (status)
	errx(1, "krb5_init_context failed: %d", status);

    status = krb5_cc_default (context, &ccache);
    if (status)
	krb5_err(context, 1, status, "krb5_cc_default");

    status = krb5_auth_con_init (context, &auth_context);
    if (status)
	krb5_err(context, 1, status, "krb5_auth_con_init");

    local_addr.addr_type = AF_INET;
    local_addr.address.length = sizeof(local.sin_addr);
    local_addr.address.data   = &local.sin_addr;

    remote_addr.addr_type = AF_INET;
    remote_addr.address.length = sizeof(remote.sin_addr);
    remote_addr.address.data   = &remote.sin_addr;

    status = krb5_auth_con_setaddrs (context,
				     auth_context,
				     &local_addr,
				     &remote_addr);
    if (status)
	krb5_err(context, 1, status, "krb5_auth_con_setaddr");

    krb5_cc_clear_mcred(&mcred);

    status = krb5_cc_get_principal(context, ccache, &client);
    if(status)
	krb5_err(context, 1, status, "krb5_cc_get_principal");
    status = krb5_make_principal(context, &mcred.server,
				 krb5_principal_get_realm(context, client),
				 "krbtgt",
				 krb5_principal_get_realm(context, client),
				 NULL);
    if(status)
	krb5_err(context, 1, status, "krb5_make_principal");
    mcred.client = client;

    status = krb5_cc_retrieve_cred(context, ccache, 0, &mcred, &cred);
    if(status)
	krb5_err(context, 1, status, "krb5_cc_retrieve_cred");

    {
	char *client_name;
	krb5_data data;
	status = krb5_unparse_name(context, cred.client, &client_name);
	if(status)
	    krb5_err(context, 1, status, "krb5_unparse_name");
	data.data = client_name;
	data.length = strlen(client_name) + 1;
	status = krb5_write_message(context, &sock, &data);
	if(status)
	    krb5_err(context, 1, status, "krb5_write_message");
	free(client_name);
    }

    status = krb5_write_message(context, &sock, &cred.ticket);
    if(status)
	krb5_err(context, 1, status, "krb5_write_message");

    status = krb5_auth_con_setuserkey(context, auth_context, &cred.session);
    if(status)
	krb5_err(context, 1, status, "krb5_auth_con_setuserkey");

    status = krb5_recvauth(context, &auth_context, &sock,
			   VERSION, client, 0, NULL, &ticket);

    if (status)
	krb5_err(context, 1, status, "krb5_recvauth");

    if (ticket->ticket.authorization_data) {
	AuthorizationData *authz;
	int i;

	printf("Authorization data:\n");

	authz = ticket->ticket.authorization_data;
	for (i = 0; i < authz->len; i++) {
	    printf("\ttype %d, length %lu\n",
		   authz->val[i].ad_type,
		   (unsigned long)authz->val[i].ad_data.length);
	}
    }

    data.data   = "hej";
    data.length = 3;

    krb5_data_zero (&packet);

    status = krb5_mk_safe (context,
			   auth_context,
			   &data,
			   &packet,
			   NULL);
    if (status)
	krb5_err(context, 1, status, "krb5_mk_safe");

    status = krb5_write_message(context, &sock, &packet);
    if(status)
	krb5_err(context, 1, status, "krb5_write_message");

    data.data   = "hemligt";
    data.length = 7;

    krb5_data_free (&packet);

    status = krb5_mk_priv (context,
			   auth_context,
			   &data,
			   &packet,
			   NULL);
    if (status)
	krb5_err(context, 1, status, "krb5_mk_priv");

    status = krb5_write_message(context, &sock, &packet);
    if(status)
	krb5_err(context, 1, status, "krb5_write_message");
    return 0;
}
Exemple #29
0
int
main(int argc, char **argv)
{
    krb5_error_code ret;

    setprogname(argv[0]);

    ret = krb5_init_context(&context);
    if (ret == KRB5_CONFIG_BADFORMAT)
	errx (1, "krb5_init_context failed to parse configuration file");
    else if (ret)
	errx (1, "krb5_init_context failed: %d", ret);

    ret = krb5_kt_register(context, &hdb_kt_ops);
    if (ret)
	errx (1, "krb5_kt_register(HDB) failed: %d", ret);

    config = configure(context, argc, argv);

#ifdef SIGPIPE
#ifdef HAVE_SIGACTION
    {
	struct sigaction sa;

	sa.sa_flags = 0;
	sigemptyset(&sa.sa_mask);

	sa.sa_handler = SIG_IGN;
	sigaction(SIGPIPE, &sa, NULL);
    }
#else
    signal(SIGPIPE, SIG_IGN);
#endif
#endif /* SIGPIPE */



#ifdef SUPPORT_DETACH
    if (detach_from_console)
	daemon(0, 0);
#endif
#ifdef __APPLE__
    if (sandbox_flag) {
	char *errorstring;
	ret = sandbox_init("kdc", SANDBOX_NAMED, &errorstring);
	if (ret)
	    errx(1, "sandbox_init failed: %d: %s", ret, errorstring);
    }
    bonjour_announce(get_realms);
#endif /* __APPLE__ */
    pidfile(NULL);

    switch_environment();

    setup_listeners(context, config, listen_on_ipc, listen_on_network);

    heim_sipc_signal_handler(SIGINT, terminated, "SIGINT");
    heim_sipc_signal_handler(SIGTERM, terminated, "SIGTERM");
#ifdef SIGXCPU
    heim_sipc_signal_handler(SIGXCPU, terminated, "CPU time limit exceeded");
#endif

    heim_ipc_main();

    krb5_free_context(context);
    return 0;
}
Exemple #30
0
int main (int argc, char **argv)
{
	TALLOC_CTX *mem_ctx = talloc_init("ktutil");
	krb5_context context;
	krb5_keytab keytab;
	krb5_kt_cursor cursor;
	krb5_keytab_entry entry;
	krb5_error_code ret;
	char *keytab_name = NULL;

	if (mem_ctx == NULL) {
		printf("talloc_init() failed\n");
		exit(1);
	}

	if (argc != 2) {
		printf("Usage: %s KEYTAB\n", argv[0]);
		exit(1);
	}

	keytab_name = argv[1];

	initialize_krb5_error_table();

	ret = krb5_init_context(&context);
	if (ret) {
		smb_krb5_err(mem_ctx, context, 1, ret, "krb5_context");
	}

	ret = smb_krb5_open_keytab_relative(context, keytab_name, false, &keytab);
	if (ret) {
		smb_krb5_err(mem_ctx, context, 1, ret, "open keytab");
	}

	ret = krb5_kt_start_seq_get(context, keytab, &cursor);
	if (ret) {
		smb_krb5_err(mem_ctx, context, 1, ret, "krb5_kt_start_seq_get");
	}

	for (ret = krb5_kt_next_entry(context, keytab, &entry, &cursor);
	     ret == 0;
	     ret = krb5_kt_next_entry(context, keytab, &entry, &cursor))
	{
		char *principal = NULL;
		char *enctype_str = NULL;
		krb5_enctype enctype = smb_get_enctype_from_kt_entry(&entry);

		ret = smb_krb5_unparse_name(mem_ctx,
					    context,
					    entry.principal,
					    &principal);
		if (ret) {
			smb_krb5_err(mem_ctx, context, 1, ret, "krb5_enctype_to_string");
		}

		ret = smb_krb5_enctype_to_string(context,
						 enctype,
						 &enctype_str);
		if (ret) {
			smb_krb5_err(mem_ctx, context, 1, ret, "krb5_enctype_to_string");
		}

		printf("%s (%s)\n", principal, enctype_str);

		TALLOC_FREE(principal);
		SAFE_FREE(enctype_str);
		smb_krb5_kt_free_entry(context, &entry);
	}

	ret = krb5_kt_end_seq_get(context, keytab, &cursor);
	if (ret) {
		smb_krb5_err(mem_ctx, context, 1, ret, "krb5_kt_end_seq_get");
	}

	ret = krb5_kt_close(context, keytab);
	if (ret) {
		smb_krb5_err(mem_ctx, context, 1, ret, "krb5_kt_close");
	}

	krb5_free_context(context);
	talloc_free(mem_ctx);
	return 0;
}