3 * Copyright (C) 2009-2024 SonarSource SA
4 * mailto:info AT sonarsource DOT com
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 3 of the License, or (at your option) any later version.
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 GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 package org.sonar.server.authentication;
22 import com.google.common.annotations.VisibleForTesting;
23 import java.security.MessageDigest;
24 import java.util.Optional;
25 import org.apache.commons.codec.digest.HmacAlgorithms;
26 import org.apache.commons.codec.digest.HmacUtils;
27 import org.sonar.api.config.internal.Encryption;
28 import org.sonar.api.config.internal.Settings;
29 import org.sonar.api.server.http.HttpRequest;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32 import org.sonar.db.DbClient;
33 import org.sonar.db.DbSession;
34 import org.sonar.db.alm.setting.ALM;
35 import org.sonar.server.authentication.event.AuthenticationEvent;
36 import org.sonar.server.authentication.event.AuthenticationException;
38 import static java.lang.String.format;
39 import static java.nio.charset.StandardCharsets.UTF_8;
40 import static java.util.stream.Collectors.joining;
41 import static org.apache.commons.lang.StringUtils.isEmpty;
42 import static org.sonar.server.user.GithubWebhookUserSession.GITHUB_WEBHOOK_USER_NAME;
44 public class GithubWebhookAuthentication {
45 private static final Logger LOG = LoggerFactory.getLogger(GithubWebhookAuthentication.class);
48 static final String GITHUB_SIGNATURE_HEADER = "x-hub-signature-256";
51 static final String GITHUB_APP_ID_HEADER = "x-github-hook-installation-target-id";
54 static final String MSG_AUTHENTICATION_FAILED = "Failed to authenticate payload from Github webhook. Either the webhook was called by unexpected clients"
55 + " or the webhook secret set in SonarQube does not match the one from Github.";
58 static final String MSG_UNAUTHENTICATED_GITHUB_CALLS_DENIED = "Unauthenticated calls from GitHub are forbidden. A webhook secret must be defined in the GitHub App with Id %s.";
61 static final String MSG_NO_WEBHOOK_SECRET_FOUND = "Webhook secret for your GitHub app with Id %s must be set in SonarQube.";
64 static final String MSG_NO_BODY_FOUND = "No body found in GitHub Webhook event.";
66 private static final String SHA_256_PREFIX = "sha256=";
68 private final AuthenticationEvent authenticationEvent;
70 private final DbClient dbClient;
72 private final Encryption encryption;
74 public GithubWebhookAuthentication(AuthenticationEvent authenticationEvent, DbClient dbClient, Settings settings) {
75 this.authenticationEvent = authenticationEvent;
76 this.dbClient = dbClient;
77 this.encryption = settings.getEncryption();
80 public Optional<UserAuthResult> authenticate(HttpRequest request) {
81 String githubAppId = request.getHeader(GITHUB_APP_ID_HEADER);
82 if (isEmpty(githubAppId)) {
83 return Optional.empty();
86 String githubSignature = getGithubSignature(request, githubAppId);
87 String body = getBody(request);
88 String webhookSecret = getWebhookSecret(githubAppId);
90 String computedSignature = computeSignature(body, webhookSecret);
91 if (!checkEqualityTimingAttacksSafe(githubSignature, computedSignature)) {
92 logAuthenticationProblemAndThrow(MSG_AUTHENTICATION_FAILED);
94 return createAuthResult(request);
97 private static String getGithubSignature(HttpRequest request, String githubAppId) {
98 String githubSignature = request.getHeader(GITHUB_SIGNATURE_HEADER);
99 if (isEmpty(githubSignature)) {
100 logAuthenticationProblemAndThrow(format(MSG_UNAUTHENTICATED_GITHUB_CALLS_DENIED, githubAppId));
102 return githubSignature;
105 private static String getBody(HttpRequest request) {
107 return request.getReader().lines().collect(joining(System.lineSeparator()));
108 } catch (Exception e) {
109 logAuthenticationProblemAndThrow(MSG_NO_BODY_FOUND);
114 private String getWebhookSecret(String githubAppId) {
115 String webhookSecret = fetchWebhookSecret(githubAppId);
116 if (isEmpty(webhookSecret)) {
117 logAuthenticationProblemAndThrow(format(MSG_NO_WEBHOOK_SECRET_FOUND, githubAppId));
119 return webhookSecret;
122 private String fetchWebhookSecret(String appId) {
123 try (DbSession dbSession = dbClient.openSession(false)) {
124 return dbClient.almSettingDao().selectByAlmAndAppId(dbSession, ALM.GITHUB, appId)
125 .map(almSettingDto -> almSettingDto.getDecryptedWebhookSecret(encryption))
130 private static void logAuthenticationProblemAndThrow(String message) {
132 throw AuthenticationException.newBuilder()
133 .setSource(AuthenticationEvent.Source.githubWebhook())
138 private static String computeSignature(String body, String webhookSecret) {
139 HmacUtils hmacUtils = new HmacUtils(HmacAlgorithms.HMAC_SHA_256, webhookSecret);
140 return SHA_256_PREFIX + hmacUtils.hmacHex(body);
143 private static boolean checkEqualityTimingAttacksSafe(String githubSignature, String computedSignature) {
144 return MessageDigest.isEqual(githubSignature.getBytes(UTF_8), computedSignature.getBytes(UTF_8));
147 private Optional<UserAuthResult> createAuthResult(HttpRequest request) {
148 UserAuthResult userAuthResult = UserAuthResult.withGithubWebhook();
149 authenticationEvent.loginSuccess(request, GITHUB_WEBHOOK_USER_NAME, AuthenticationEvent.Source.githubWebhook());
150 return Optional.of(userAuthResult);