162306a36Sopenharmony_ci// SPDX-License-Identifier: GPL-2.0
262306a36Sopenharmony_ci/*
362306a36Sopenharmony_ci * Implementations of the security context functions.
462306a36Sopenharmony_ci *
562306a36Sopenharmony_ci * Author: Ondrej Mosnacek <omosnacek@gmail.com>
662306a36Sopenharmony_ci * Copyright (C) 2020 Red Hat, Inc.
762306a36Sopenharmony_ci */
862306a36Sopenharmony_ci
962306a36Sopenharmony_ci#include <linux/jhash.h>
1062306a36Sopenharmony_ci
1162306a36Sopenharmony_ci#include "context.h"
1262306a36Sopenharmony_ci#include "mls.h"
1362306a36Sopenharmony_ci
1462306a36Sopenharmony_ciu32 context_compute_hash(const struct context *c)
1562306a36Sopenharmony_ci{
1662306a36Sopenharmony_ci	u32 hash = 0;
1762306a36Sopenharmony_ci
1862306a36Sopenharmony_ci	/*
1962306a36Sopenharmony_ci	 * If a context is invalid, it will always be represented by a
2062306a36Sopenharmony_ci	 * context struct with only the len & str set (and vice versa)
2162306a36Sopenharmony_ci	 * under a given policy. Since context structs from different
2262306a36Sopenharmony_ci	 * policies should never meet, it is safe to hash valid and
2362306a36Sopenharmony_ci	 * invalid contexts differently. The context_cmp() function
2462306a36Sopenharmony_ci	 * already operates under the same assumption.
2562306a36Sopenharmony_ci	 */
2662306a36Sopenharmony_ci	if (c->len)
2762306a36Sopenharmony_ci		return full_name_hash(NULL, c->str, c->len);
2862306a36Sopenharmony_ci
2962306a36Sopenharmony_ci	hash = jhash_3words(c->user, c->role, c->type, hash);
3062306a36Sopenharmony_ci	hash = mls_range_hash(&c->range, hash);
3162306a36Sopenharmony_ci	return hash;
3262306a36Sopenharmony_ci}
33