Created
October 29, 2018 10:44
-
-
Save CoditCompany/79b28dc22d129ef2380251538a511c1d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#r "System.Security" | |
using System.Net; | |
using System.Text; | |
using System.Security.Cryptography; | |
private const string Sha1Prefix = "sha1="; | |
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log) | |
{ | |
log.Info("C# HTTP trigger function processed a request."); | |
string signatureWithPrefix = req.Headers.GetValues("X-Hub-Signature").FirstOrDefault(); | |
log.Info("Signature: " + signatureWithPrefix); | |
string sharedSecret = req.Headers.GetValues("X-LogicApp-Secret").FirstOrDefault(); | |
log.Info("Secret: " + sharedSecret); | |
var payload = await req.Content.ReadAsStringAsync(); | |
log.Info("Payload: " + payload); | |
bool isValid = IsGithubPushAllowed(payload, signatureWithPrefix, sharedSecret); | |
return isValid == false | |
? req.CreateResponse(HttpStatusCode.BadRequest, "Missing or invalid Github security headers!") | |
: req.CreateResponse(HttpStatusCode.OK); | |
} | |
public static bool IsGithubPushAllowed(string payload, string signatureWithPrefix, string sharedSecret) | |
{ | |
if (string.IsNullOrWhiteSpace(payload)) | |
{ | |
throw new ArgumentNullException(nameof(payload)); | |
} | |
if (string.IsNullOrWhiteSpace(signatureWithPrefix)) | |
{ | |
throw new ArgumentNullException(nameof(signatureWithPrefix)); | |
} | |
if (signatureWithPrefix.StartsWith(Sha1Prefix, StringComparison.OrdinalIgnoreCase)) | |
{ | |
var signature = signatureWithPrefix.Substring(Sha1Prefix.Length); | |
var secret = Encoding.ASCII.GetBytes(sharedSecret); | |
var payloadBytes = Encoding.ASCII.GetBytes(payload); | |
using (var hmSha1 = new HMACSHA1(secret)) | |
{ | |
var hash = hmSha1.ComputeHash(payloadBytes); | |
var hashString = ToHexString(hash); | |
if (hashString.Equals(signature)) | |
{ | |
return true; | |
} | |
} | |
} | |
return false; | |
} | |
public static string ToHexString(byte[] bytes) | |
{ | |
var builder = new StringBuilder(bytes.Length * 2); | |
foreach (byte b in bytes) | |
{ | |
builder.AppendFormat("{0:x2}", b); | |
} | |
return builder.ToString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment