Asp.Net核心SAML响应签名验证

时间:2017-12-05 20:42:26

标签: c# asp.net-core saml-2.0 xml-signature

我正在处理需要使用第三方idP(SP启动)实施SAML SSO的Web应用程序。我已经达到了从idP收到SAMLResponse的程度,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" InResponseTo="63622fa6-9a00-4d39-9c92-791c3a1efc3f" IssueInstant="2017-12-04T13:47:30Z" ID="mjmobamignjdlgkpmkiijfbknamlbkadhkjcamhp" Version="2.0">
  <saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">https://idp.com</saml:Issuer>
  <samlp:Status>
    <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
  </samlp:Status>
  <saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="gkifgihgclegelojncjfgegcddfncgdaefcjgbod" IssueInstant="2017-12-04T13:47:30Z" Version="2.0">
    <saml:Issuer>https://idp.com</saml:Issuer>
    <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
      <ds:SignedInfo>
        <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
        <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
        <ds:Reference URI="#gkifgihgclegelojncjfgegcddfncgdaefcjgbod">
          <ds:Transforms>
            <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
            <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
          </ds:Transforms>
          <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
          <ds:DigestValue>nyU3iydIomlY9+D+YO7E6zNyq1A=</ds:DigestValue>
        </ds:Reference>
      </ds:SignedInfo>
      <ds:SignatureValue>1AVSFcmgaPMFZvPHYyZDz1oFWzgiMCHI6yMfe6yCSK1pw6bkbZd/yZys8DuySi3Q75bnu3FmbrJQ
L9eEfoXK7kJEut79f9xrBwScNYQ21AZdYh5Rdzm7jRsbugYuQpfUUWasR6U37+bStVPpsCYEo4+C
Y1arLC/9ujj7aGxF7H+EMk7X0L4059+2v711X7a/3biowx2CyNOgjNRcrri3cyX/0soryyCA6/zH
fO2wcQi4udMXcZwXtZpAsluah7DjGp9MSTS5NInKm3Is4VIS9fN3KmKKTJYYZI27N0lFAxgHGVXc
GPWsh4hAd1CqQvuM0P5YlBfgPBD6Mu6tmZ9VLg==</ds:SignatureValue>
      <ds:KeyInfo>
        <ds:X509IssuerSerial>
          <ds:X509IssuerName>CN=Symantec Class 3 Secure Server CA - G4,OU=Symantec Trust Network,O=Symantec Corporation,C=US</ds:X509IssuerName>
          <ds:X509SerialNumber>142421751065451577073995987482935596892</ds:X509SerialNumber>
        </ds:X509IssuerSerial>
        <ds:X509Data>
          <ds:X509Certificate>MIIGfDCCBWSgAwIBAgIQayVud3+bDrNKrbQphkCXXDANBgkqhkiG9w0BAQsFADB+MQswCQYDVQQG
EwJVUzEdMBsGA1UEChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xHzAdBgNVBAsTFlN5bWFudGVjIFRy
dXN0IE5ldHdvcmsxLzAtBgNVBAMTJlN5bWFudGVjIENsYXNzIDMgU2VjdXJlIFNlcnZlciBDQSAt
IEc0MB4XDTE2MTEyNTAwMDAwMFoXDTE4MTEyNjIzNTk1OVowgYExCzAJBgNVBAYTAlVTMREwDwYD
VQQIDAhOZXcgWW9yazERMA8GA1UEBwwITmV3IFlvcmsxGDAWBgNVBAoMD1Rob21zb24gUmV1dGVy
czEMMAoGA1UECwwDTUlTMSQwIgYDVQQDDBtzYWZlc2FtbC50aG9tc29ucmV1dGVycy5jb20wggEi
MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDakNsHCqwMaX1VO11VQwzS3eFIOEYr78EMvX3v
lxYO5F41NBEslkFVUD5RzFOXwpUhNzHPHd7IkECUtdrJlkmwWdpdIPC2exf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SFVZgIhANurB8rz4rAPmnEENCIK1Kdr
t6iDAF15THY8lWuGtFS3AHUAvHjh38X2PGhGSTNNoQ+hXwl5aSAJwIG08/aRfz7ZuKUAAAFYm25O
wwAABAMARjBEAiBMFlg9dANwKJ8vMltapsWGeQotN3tklnlApUxlVduOwwIgA0HHsKr1qgryF6fY
04k53uYxoeVoqk1elaAHi+K6JmMwDQYJKoZIhvcNAQELBQADggEBAByVHCZzKL9iVhg2Ypw6Xqxl
UcetruvMZJHUCZeH1eHmre4EMw97JQ5JH/QAftjoqN/mxa9DlSxaOBDMmVlFcLjOs60UVHFb8FVV
ScBpuogrztg8oPc+XRhaKTLmdsL32agQUdH+TAvhs8TOqxJlENk50iILrAxnYcadOWo1A0nJnZIF
N8qfbyTFoojQj0jBnIThNeDP8RR4m7kAba2Y9PiE7YeQWUPUGepUhQT76zivX81TmdGJo0IZ4Jjd
xdtyyK90STS73tOq1jUnUUqkb8zyTPgkSC/MDnFzuWSie4CWgfw0KSKPNEmra6nlH/2y+YckVYMi
TyU0Bbc2VGLlcP8=</ds:X509Certificate>
        </ds:X509Data>
      </ds:KeyInfo>
    </ds:Signature>
    <saml:Subject>
      <saml:NameID Format="urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified">C229699</saml:NameID>
      <saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
        <saml:SubjectConfirmationData InResponseTo="63622fa6-9a00-4d39-9c92-791c3a1efc3f" NotOnOrAfter="2017-12-04T13:57:30Z" Recipient="http://my-app.net/saml"/>
      </saml:SubjectConfirmation>
    </saml:Subject>
    <saml:Conditions NotBefore="2017-12-04T13:42:30Z" NotOnOrAfter="2017-12-04T13:57:30Z">
      <saml:AudienceRestriction>
        <saml:Audience>http://my-app.net</saml:Audience>
      </saml:AudienceRestriction>
    </saml:Conditions>
    <saml:AuthnStatement AuthnInstant="2017-12-04T13:47:30Z" SessionIndex="gkifgihgclegelojncjfgegcddfncgdaefcjgbod">
      <saml:AuthnContext>
        <saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified</saml:AuthnContextClassRef>
      </saml:AuthnContext>
    </saml:AuthnStatement>
    <saml:AttributeStatement>
      <saml:Attribute Name="UserID" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">
        <saml:AttributeValue>D100000</saml:AttributeValue>
      </saml:Attribute>
    </saml:AttributeStatement>
  </saml:Assertion>
</samlp:Response>

要求它是针对netcoreapp2.0的手动实现,因此我一直在尝试提供适当的解决方案来验证所提供的签名值。此文档How to: Verify the Digital Signatures of XML Documents有助于解释某些过程,但我的SSO实施需要进一步验证。

要从SAML响应中提取xml表单,我有以下块:

var samlResponse = Request.Form["SAMLResponse"];
var toBytes = Convert.FromBase64String(samlResponse);
string decodedString = 
Encoding.UTF8.GetString(toBytes);

只是为了快速参考而不打开上面的链接,这就是代码的样子(在适用的情况下使用我的样本值/变量):

CspParameters cspParams = new CspParameters();
cspParams.KeyContainerName = "XML_DSIG_RSA_KEY";

// Create a new RSA signing key and save it in the container. 
RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);

// Create a new XML document.
XmlDocument xmlDoc = new XmlDocument();

// Load an XML file into the XmlDocument object.
xmlDoc.PreserveWhitespace = true;
xmlDoc.LoadXml(decodedString);

// Verify the signature of the signed XML.
Console.WriteLine("Verifying signature...");
bool result = VerifyXml(xmlDoc, rsaKey);

// Display the results of the signature verification to 
// the console.
if (result)
{
    Console.WriteLine("The XML signature is valid.");
}
else
{
    Console.WriteLine("The XML signature is not valid.");
}

public static Boolean VerifyXml(XmlDocument Doc, RSA Key)
{
    // Check arguments.
    if (Doc == null)
        throw new ArgumentException("Doc");
    if (Key == null)
        throw new ArgumentException("Key");

    // Create a new SignedXml object and pass it
    // the XML document class.
    SignedXml signedXml = new SignedXml(Doc);

    // Find the "Signature" node and create a new
    // XmlNodeList object.
    XmlNodeList nodeList = Doc.GetElementsByTagName("Signature");

    // Throw an exception if no signature was found.
    if (nodeList.Count <= 0)
    {
        throw new CryptographicException("Verification failed: No Signature was found in the document.");
    }

    // This example only supports one signature for
    // the entire XML document.  Throw an exception 
    // if more than one signature was found.
    if (nodeList.Count >= 2)
    {
        throw new CryptographicException("Verification failed: More that one signature was found for the document.");
    }

    // Load the first <signature> node.  
    signedXml.LoadXml((XmlElement)nodeList[0]);

    // Check the signature and return the result.
    return signedXml.CheckSignature(Key);
}

更新:我在Asp.Net Core 2.0中手动实现SAML SSO的工作解决方案:首先,我将以下方法命名为&#34; VerifyXml&#34;验证从SAML响应表单数据检索的Xml文档的签名。然后我将我的AccountController代码中的X509证书验证为@Evk(再次感谢帮助),指出仅仅验证签名是不够的,在这种情况下,是为了防止发送和接受任意SAML响应。除了验证这两个值之外,在我的情况下,我还需要验证&#34; InResponseTo&#34;参数匹配我的网络应用程序(SP)在合理的时间段内生成的值。通常,登录不需要很长时间,因此您可以创建一项任务,以忘记在经过一定时间后由您的Web应用程序生成和发布的AuthnRequest ID;说一分钟或适用于您的时间段(未在答案中包含此代码)。

public static bool VerifyXml(XmlDocument Doc)
{
    // Check document isn't null.
    if (Doc == null) 
        throw new ArgumentException("Doc");    
    SignedXml signedXml = new SignedXml(Doc);
    var nsManager = new XmlNamespaceManager(Doc.NameTable);
    nsManager.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
    var node = Doc.SelectSingleNode("//ds:Signature", nsManager);
    signedXml.LoadXml((XmlElement)node);
    return signedXml.CheckSignature();
 }
/* ******* CONTROLLER CODE ******* */
SignedXml signedXml = new SignedXml(xdoc);
var nsManager = new XmlNamespaceManager(xdoc.NameTable);
nsManager.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
var certElement = xdoc.SelectSingleNode("//ds:X509Certificate", nsManager);
/* Convert the received X509 Certificate into a new X509Certificate2 object. */
var certReceived = new X509Certificate2(Convert.FromBase64String(certElement.InnerText));
/* Load the pre-shared X509 Certificate from the idP metadata file. I have it stored in a secure database (You DO NOT want this stored in an easily accessible place, especially for production, in the project as it contains sensitive information). */
var loadSafeCert = _context.StoredMetadata.Where(metadata => idPMetadata.Certificate == "Certificate").FirstOrDefault();
/* Create a new X509Certificate2 using the value of the pre-defined certificate. */    
var safeCertificate = new X509Certificate2(Convert.FromBase64String(loadSafeCert.ConfigurationValue));    
/* Compare the received X509 Certificate value vs the pre-defined X509 Certificate value to ensure the validity. */
if (certReceived.GetPublicKeyString() == safeCertificate.GetPublicKeyString())
{ /* Store/get attributes, authenticate user, etc here */ }

2 个答案:

答案 0 :(得分:3)

尝试验证这样的签名(您不会对我进行验证,但这可能是由在此处发布时所做的更改引起的):

public static bool VerifyXml(XmlDocument Doc) {
    if (Doc == null)
        throw new ArgumentException("Doc");
    SignedXml signedXml = new SignedXml(Doc);
    var nsManager = new XmlNamespaceManager(Doc.NameTable);
    nsManager.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
    var node = Doc.SelectSingleNode("//ds:Signature", nsManager);
    // find signature node
    var certElement = Doc.SelectSingleNode("//ds:X509Certificate", nsManager);
    // find certificate node
    var cert = new X509Certificate2(Convert.FromBase64String(certElement.InnerText));            
    signedXml.LoadXml((XmlElement)node);
    return signedXml.CheckSignature(cert);
}

如果这不起作用,也请尝试相同但调用

return signedXml.CheckSignature();

而不是

return signedXml.CheckSignature(cert);

请注意,仅验证此签名不足以确保响应未被篡改。您使用响应本身(X509Data)中提供的密钥验证签名,这意味着攻击者可以截获响应,提取信息并使用自己的密钥对其进行重新签名,因此签名将有效,但签署的密钥将不会。因此,在提取证书(或者您可以使用signedXml.CheckSignatureReturningKey方法获取与签名相关的公钥)之后,您需要验证它是否有效以及您期望的证书(例如通过比较它的散列与您期望的证书散列。)

答案 1 :(得分:1)

签名应通过身份提供商提供的证书进行验证。从更新开始,您将从IdP存储元数据xml,然后从中检索证书。

另一种替代方法是从IdP作为.cer文件获取证书,并将其安装在Trusted Root Certificate Athorities的{​​{1}}存储中。安装后,可以使用代码对其进行访问并用于验证签名。这样,您不必担心XML中证书的欺骗。

在这种方法中,响应XML中的证书用于获取序列号,通过该序列号可以在商店中找到保存的证书。

以@Evk的响应为基础

Local Machine

public static bool VerifyXml(XmlDocument Doc) 
{
    if (Doc == null)
        throw new ArgumentException("Doc");
    SignedXml signedXml = new SignedXml(Doc);
    var nsManager = new XmlNamespaceManager(Doc.NameTable);
    nsManager.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
    var node = Doc.SelectSingleNode("//ds:Signature", nsManager);
    // find signature node
    var certElement = Doc.SelectSingleNode("//ds:X509Certificate", nsManager);
    // find certificate node
    var cert = new X509Certificate2(Convert.FromBase64String(certElement.InnerText));            
    signedXml.LoadXml((XmlElement)node);

    //Find installed certificate from store
    X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
    store.Open(OpenFlags.ReadOnly);
    X509Certificate2 storeCert = store.Certificates.Find(X509FindType.FindBySerialNumber, cert.SerialNumber, true)[0];

    return signedXml.CheckSignature(storeCert, true);
    //^^^ If certificate is installed in the Root location then 
    //this method returns true after validating it as well
    //In addition to validating the signature
}