File: SubresourceIntegrity.cpp

package info (click to toggle)
chromium-browser 41.0.2272.118-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-kfreebsd
  • size: 2,189,132 kB
  • sloc: cpp: 9,691,462; ansic: 3,341,451; python: 712,689; asm: 518,779; xml: 208,926; java: 169,820; sh: 119,353; perl: 68,907; makefile: 28,311; yacc: 13,305; objc: 11,385; tcl: 3,186; cs: 2,225; sql: 2,217; lex: 2,215; lisp: 1,349; pascal: 1,256; awk: 407; ruby: 155; sed: 53; php: 14; exp: 11
file content (301 lines) | stat: -rw-r--r-- 11,822 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "config.h"
#include "core/frame/SubresourceIntegrity.h"

#include "core/HTMLNames.h"
#include "core/dom/Document.h"
#include "core/dom/Element.h"
#include "core/frame/ConsoleTypes.h"
#include "core/frame/UseCounter.h"
#include "core/inspector/ConsoleMessage.h"
#include "platform/Crypto.h"
#include "platform/ParsingUtilities.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/weborigin/KURL.h"
#include "platform/weborigin/SecurityOrigin.h"
#include "public/platform/WebCrypto.h"
#include "public/platform/WebCryptoAlgorithm.h"
#include "wtf/ASCIICType.h"
#include "wtf/text/Base64.h"
#include "wtf/text/StringUTF8Adaptor.h"
#include "wtf/text/WTFString.h"

namespace blink {

// FIXME: This should probably use common functions with ContentSecurityPolicy.
static bool isIntegrityCharacter(UChar c)
{
    // Check if it's a base64 encoded value. We're pretty loose here, as there's
    // not much risk in it, and it'll make it simpler for developers.
    return isASCIIAlphanumeric(c) || c == '_' || c == '-' || c == '+' || c == '/' || c == '=';
}

static bool isTypeCharacter(UChar c)
{
    return isASCIIAlphanumeric(c) || c == '+' || c == '.' || c == '-';
}

static void logErrorToConsole(const String& message, Document& document)
{
    document.addConsoleMessage(ConsoleMessage::create(SecurityMessageSource, ErrorMessageLevel, message));
}

static bool DigestsEqual(const DigestValue& digest1, const DigestValue& digest2)
{
    if (digest1.size() != digest2.size())
        return false;

    for (size_t i = 0; i < digest1.size(); i++) {
        if (digest1[i] != digest2[i])
            return false;
    }

    return true;
}

static String algorithmToString(HashAlgorithm algorithm)
{
    static const struct {
        HashAlgorithm algorithm;
        const char* name;
    } kAlgorithmToString[] = {
        {  HashAlgorithmSha256, "SHA-256" },
        {  HashAlgorithmSha384, "SHA-384" },
        {  HashAlgorithmSha512, "SHA-512" }
    };

    for (const auto& algorithmToString : kAlgorithmToString) {
        if (algorithmToString.algorithm == algorithm)
            return algorithmToString.name;
    }

    ASSERT_NOT_REACHED();
    return String();
}

static String digestToString(const DigestValue& digest)
{
    // We always output base64url encoded data, even though we use base64 internally.
    String output = base64Encode(reinterpret_cast<const char*>(digest.data()), digest.size(), Base64DoNotInsertLFs);
    return output.replace('+', '-').replace('/', '_');
}

bool SubresourceIntegrity::CheckSubresourceIntegrity(const Element& element, const String& source, const KURL& resourceUrl, const String& resourceType)
{
    if (!RuntimeEnabledFeatures::subresourceIntegrityEnabled())
        return true;

    if (!element.fastHasAttribute(HTMLNames::integrityAttr))
        return true;

    Document& document = element.document();

    // Instead of just checking SecurityOrigin::isSecure on resourceUrl, this
    // checks canAccessFeatureRequiringSecureOrigin so that file:// protocols
    // and localhost resources can be allowed. These may be useful for testing
    // and are allowed for features requiring authenticated origins, so Chrome
    // allows them here.
    String insecureOriginMsg = "";
    RefPtr<SecurityOrigin> resourceSecurityOrigin = SecurityOrigin::create(resourceUrl);
    if (!document.securityOrigin()->canAccessFeatureRequiringSecureOrigin(insecureOriginMsg)) {
        UseCounter::count(document, UseCounter::SRIElementWithIntegrityAttributeAndInsecureOrigin);
        // FIXME: This console message should probably utilize
        // inesecureOriginMsg to give a more helpful message to the user.
        logErrorToConsole("The 'integrity' attribute may only be used in documents in secure origins.", document);
        return false;
    }
    if (!resourceSecurityOrigin->canAccessFeatureRequiringSecureOrigin(insecureOriginMsg)) {
        UseCounter::count(document, UseCounter::SRIElementWithIntegrityAttributeAndInsecureResource);
        logErrorToConsole("The 'integrity' attribute may only be used with resources on secure origins.", document);
        return false;
    }

    String integrity;
    HashAlgorithm algorithm;
    String type;
    String attribute = element.fastGetAttribute(HTMLNames::integrityAttr);
    if (!parseIntegrityAttribute(attribute, integrity, algorithm, type, document)) {
        // An error is logged to the console during parsing; we don't need to log one here.
        UseCounter::count(document, UseCounter::SRIElementWithUnparsableIntegrityAttribute);
        return false;
    }

    if (!type.isEmpty() && !equalIgnoringCase(type, resourceType)) {
        UseCounter::count(document, UseCounter::SRIElementWithNonMatchingIntegrityType);
        logErrorToConsole("Subresource Integrity: The resource '" + resourceUrl.elidedString() + "' was delivered as type '" + resourceType + "', which does not match the expected type '" + type + "'. The resource has been blocked.", document);
        return false;
    }

    Vector<char> hashVector;
    base64Decode(integrity, hashVector);

    StringUTF8Adaptor normalizedSource(source, StringUTF8Adaptor::Normalize, WTF::EntitiesForUnencodables);

    DigestValue digest;
    bool digestSuccess = computeDigest(algorithm, normalizedSource.data(), normalizedSource.length(), digest);

    if (digestSuccess) {
        DigestValue convertedHashVector;
        convertedHashVector.append(reinterpret_cast<uint8_t*>(hashVector.data()), hashVector.size());
        if (DigestsEqual(digest, convertedHashVector)) {
            UseCounter::count(document, UseCounter::SRIElementWithMatchingIntegrityAttribute);
            return true;
        } else {
            // This message exposes the digest of the resource to the console.
            // Because this is only to the console, that's okay for now, but we
            // need to be very careful not to expose this in exceptions or
            // JavaScript, otherwise it risks exposing information about the
            // resource cross-origin.
            logErrorToConsole("The computed " + algorithmToString(algorithm) + " integrity '" + digestToString(digest) + "' does not match the 'integrity' attribute '" + integrity + "' for resource '" + resourceUrl.elidedString() + "'.", document);
        }
    } else {
        logErrorToConsole("There was an error computing an 'integrity' value for resource '" + resourceUrl.elidedString() + "'.", document);
    }

    UseCounter::count(document, UseCounter::SRIElementWithNonMatchingIntegrityAttribute);
    return false;
}

// Before:
//
// ni:///[algorithm];[hash]
//       ^                 ^
//       position          end
//
// After (if successful: if the method returns false, we make no promises and the caller should exit early):
//
// ni:///[algorithm];[hash]
//                  ^      ^
//           position    end
bool SubresourceIntegrity::parseAlgorithm(const UChar*& position, const UChar* end, HashAlgorithm& algorithm)
{
    // Any additions or subtractions from this struct should also modify the
    // respective entries in the kAlgorithmMap array in checkDigest() as well
    // as the array in algorithmToString().
    static const struct {
        const char* prefix;
        HashAlgorithm algorithm;
    } kSupportedPrefixes[] = {
        { "sha256", HashAlgorithmSha256 },
        { "sha-256", HashAlgorithmSha256 },
        { "sha384", HashAlgorithmSha384 },
        { "sha-384", HashAlgorithmSha384 },
        { "sha512", HashAlgorithmSha512 },
        { "sha-512", HashAlgorithmSha512 }
    };

    for (auto& prefix : kSupportedPrefixes) {
        if (skipToken<UChar>(position, end, prefix.prefix)) {
            algorithm = prefix.algorithm;
            return true;
        }
    }

    return false;
}

// Before:
//
// ni:///[algorithm];[hash]     OR      ni:///[algorithm];[hash]?[params]
//                   ^     ^                              ^              ^
//            position   end                       position            end
//
// After (if successful: if the method returns false, we make no promises and the caller should exit early):
//
// ni:///[algorithm];[hash]     OR      ni:///[algorithm];[hash]?[params]
//                         ^                                    ^        ^
//                         position/end                  position      end
bool SubresourceIntegrity::parseDigest(const UChar*& position, const UChar* end, String& digest)
{
    const UChar* begin = position;
    skipWhile<UChar, isIntegrityCharacter>(position, end);

    if (position == begin || (position != end && *position != '?')) {
        digest = emptyString();
        return false;
    }

    // We accept base64url encoding, but normalize to "normal" base64 internally:
    digest = String(begin, position - begin).replace('-', '+').replace('_', '/');
    return true;
}


// Before:
//
// ni:///[algorithm];[hash]     OR      ni:///[algorithm];[hash]?[params]
//                         ^                                    ^        ^
//              position/end                             position      end
//
// After (if successful: if the method returns false, we make no promises and the caller should exit early):
//
// ni:///[algorithm];[hash]     OR      ni:///[algorithm];[hash]?[params]
//                         ^                                             ^
//              position/end                                  position/end
bool SubresourceIntegrity::parseMimeType(const UChar*& position, const UChar* end, String& type)
{
    type = emptyString();
    if (position == end)
        return true;

    if (!skipToken<UChar>(position, end, "?ct="))
        return false;

    const UChar* begin = position;
    skipWhile<UChar, isASCIIAlpha>(position, end);
    if (position == end)
        return false;

    if (!skipExactly<UChar>(position, end, '/'))
        return false;

    if (position == end)
        return false;

    skipWhile<UChar, isTypeCharacter>(position, end);
    if (position != end)
        return false;

    type = String(begin, position - begin);
    return true;
}

bool SubresourceIntegrity::parseIntegrityAttribute(const String& attribute, String& digest, HashAlgorithm& algorithm, String& type, Document& document)
{
    Vector<UChar> characters;
    attribute.stripWhiteSpace().appendTo(characters);
    const UChar* position = characters.data();
    const UChar* end = characters.end();

    if (!skipToken<UChar>(position, end, "ni:///")) {
        logErrorToConsole("Error parsing 'integrity' attribute ('" + attribute + "'). The value must begin with 'ni:///'.", document);
        return false;
    }

    if (!parseAlgorithm(position, end, algorithm)) {
        logErrorToConsole("Error parsing 'integrity' attribute ('" + attribute + "'). The specified hash algorithm must be one of 'sha256', 'sha384', or 'sha512'.", document);
        return false;
    }

    if (!skipExactly<UChar>(position, end, ';')) {
        logErrorToConsole("Error parsing 'integrity' attribute ('" + attribute + "'). The hash algorithm must be followed by a ';' character.", document);
        return false;
    }

    if (!parseDigest(position, end, digest)) {
        logErrorToConsole("Error parsing 'integrity' attribute ('" + attribute + "'). The digest must be a valid, base64-encoded value.", document);
        return false;
    }

    if (!parseMimeType(position, end, type)) {
        logErrorToConsole("Error parsing 'integrity' attribute ('" + attribute + "'). The content type could not be parsed.", document);
        return false;
    }

    return true;
}

} // namespace blink