|
| 1 | +#Entity Framework Core Threat-Model |
| 2 | + |
| 3 | +Entity Framework Core is a lightweight, extensible, open source and cross-platform version of the popular Entity Framework data access technology. |
| 4 | + |
| 5 | +EF Core can serve as an object-relational mapper (O/RM), enabling .NET developers to work with a database using .NET objects, and eliminating the need for most of the data-access code they usually need to write. |
| 6 | + |
| 7 | +##Data flows |
| 8 | + |
| 9 | +A query, usually with data in parameters, is sent to the database, then a response, usually with data, is received from the database. |
| 10 | + |
| 11 | +##Trust boundaries |
| 12 | + |
| 13 | +* Communication with the database |
| 14 | +* EF is a layer on top of the lower-level database driver or SDK (e.g. SqlClient for SQL Server) and relies on it securing the connection to the database. |
| 15 | +* Logging, diagnostics |
| 16 | +* EF doesn't offer any built-in sinks for logging or diagnostics. This is only considered a trust boundary as part of the defense in depth strategy. |
| 17 | +* Loading migration assembly for migration operations at runtime |
| 18 | +* The name of the migration assembly to load must be specified in the DbContext options: |
| 19 | + |
| 20 | +```csharp |
| 21 | +services.AddDbContext<ApplicationDbContext>(options=>options.UseSqlServer( |
| 22 | +x=>x.MigrationsAssembly("WebApplication1.Migrations"))); |
| 23 | + ``` |
| 24 | + |
| 25 | +*An `Assembly`instancecanbeusedinsteadofthestring. |
| 26 | +*Whenunspecified,the `ApplicationDbContext`assemblywillbeused. |
| 27 | +*Assemblyloadingbytoolingduringdesignandbuild-time |
| 28 | +*TheEFtoolsbuildthespecifiedprojectandloadtheassemblyspecifiedbythe `TargetFileName`MSBuildproperty. |
| 29 | +*TheEFtoolsaredistributedinseparateNuGetpackages- `dotnet-ef`, `Microsoft.EntityFrameworkCore.Tools`, `Microsoft.EntityFrameworkCore.Tasks`.Thesearemeantonlytoprovidedesign-timefunctionalityandshouldn't be deployed with the app. |
| 30 | +*Multi-tenantapplications |
| 31 | +*Thisthreatmodelassumesthatalltenantsusingagivenappinstancehavethesametrustlevel.Developersareresponsibleforisolatinguntrustedtenants. |
| 32 | + |
| 33 | +###Untrusted/unknowndatabases |
| 34 | + |
| 35 | +AtrustboundaryexistsbetweenEFandthedatabaseitconnectsto;thatis,EFsupportsuntrustedresultsetscomingfromthedatabase.Thismeansthattherearenoknownexploits**viaEF**usingmaliciousdatabasecontents. |
| 36 | + |
| 37 | +EFcontainsa "scaffolding"feature,whichexaminesthemetadataofanexistingdatabase (tables,columns)andgenerates .NETcodewhichcanbeusedtoaccessthatdatabase.Asaspecificcaseofguaranteedetailedjustabove,EFguaranteesthatsuchscaffoldedcode -whichisgeneratedbasedone.g.tableandcolumnnamesinthescaffoldeddatabase -issafetorun,andcannotbeusedasavectorfore.g.aremotecodeexecutionattackviaamaliciouslycraftedtablename. |
| 38 | + |
| 39 | +####Exercisecautionwithuntrusted/unknowndatabases |
| 40 | + |
| 41 | +However,connectingandinteractingwithanunknown/untrusteddatabasesinherentlyandunavoidablybringssubstantialriskswithit,whichgobeyondattacksspecificallyagainstEFitself.Forexample,anunknowndatabasecancontainhugeamountsofdataasaformofattack:dependingonhowtheapplicationqueriesthedatabaseandwhatitdoeswiththeresults,aqueryagainstsuchamaliciouslyhugedatasetcouldproduceadenialofservice (thiswouldbeavulnerabilityintheapplication,notinEF).SQLJOINsinrelationaldatabasecanexacerbatethisproblembycausingarelativelysmalldatasettoproduceahugequeryresultset (viatheso-called "cartesianexplosion"phenomenon).SpecialcareshouldbetakenwhenemployingJOINsagainstuntrusteddatabases. |
| 42 | + |
| 43 | +Tosummarize,whileEFnarrowlyguaranteesthatitsowncodeshallnotbevulnerabletosecurityattacksviadatareturnedfromthedatabase,applicationcodeusingEFmaycontainsuchvulnerabilities,whichareoutsideofEF'sscopeofresponsibility.Asaresult,andregardlessoftheEFguaranteeprovidedabove,wehighlyrecommendproceedingwithextremecautionwhenconnectingtodatabaseswhoseoriginandcontentsareunknown |
| 44 | + |
| 45 | +##Storageofsecrets |
| 46 | + |
| 47 | +EFdoesn'tstoreanysecrets,itonlypassesthroughtheconnectionstringtotheunderlyingdatabaseprovider. |
| 48 | + |
| 49 | +However,ifthesuppliedconnectionstringisoftheformat `name=MyConnection`EFwillusethe `IConfiguration`servicefromtheserviceproviderwhere `DbContext`wasregisteredtoresolve `"MyConnection"`or `"ConnectionStrings:MyConnection"`.See [connectionstringdocumentation](https://learn.microsoft.com/ef/core/miscellaneous/connection-strings#aspnet-core) for more details. |
| 50 | +
|
| 51 | +##Serialization |
| 52 | + |
| 53 | +*JSON (de)serializerofsomepayloads (Utf8JsonWriter/Utf8JsonReader) |
| 54 | +*Composingandreceivingdatafromthedatabaseserver.EFreliesonthedatabasedriverforthelow-level (de)serializationinvolvedinthedatabasecommunicationprotocol. |
| 55 | + |
| 56 | +###Dataformat |
| 57 | + |
| 58 | +EFdoesn'tload,constructorexecutecodedynamicallybasedonthedatareceivedfromthedatabase.Alltypesarespecifiedinthemodelinadvance.Themodelisconsideredtrusted. |
| 59 | + |
| 60 | +ForJSONEFexpectsthepropertynamestobetheexactlythesameasconfiguredinthemodel,similarlyforcolumnnamesin `DbDataReader`.Extradatawillbeeitherignoredorresultinanexception.ForduplicatedJSONpropertiesthelastvaluewilltakeprecedence. |
| 61 | + |
| 62 | +EFdoesn'tassumeanyparticularorderforpropertieswhendeserializing.Duringserializationdiscriminator (`$type`)comesfirst,thenkeys,thentherestinadeterministicorder. |
| 63 | + |
| 64 | +OnlyconfigurationintheEFmodelwillbeusedtodeterminetheexpecteddatashapeandhowtheentityobjectwillbecreated, [someattributesonentitytypecaninfluencethis](https://learn.microsoft.com/ef/core/modeling/#use-data-annotations-to-configure-a-model), but attributes that affect JSON (de)serialization outside EF like `[JsonPropertyName("")]` are ignored. |
| 65 | +
|
| 66 | +ThereisnoAPIthatcanbeusedbythedevelopertoprovideaJSONstringora `DbDataReader`tobedeserialized,thisishandledinternallybytheproviderforaspecificdatabase. |
| 67 | + |
| 68 | +EFprovidersandpluginscanextendorreplacesomeofthe (de)serializationlogicandcouldintroducevulnurabilities. |
| 69 | + |
| 70 | +###Exceptions |
| 71 | + |
| 72 | +Bydefault,alldataiscensoredinexceptionmessages.Schemainformationlikepropertyandcolumnnamesisnotconsideredsensitive. |
| 73 | + |
| 74 | +###Recursiveness |
| 75 | + |
| 76 | +JSONsupportsrecursiveprimitivecollections.AndforrelationaldataEFsupportsself-joins,butinbothcasesthedeveloperhastoexplicitlysettherecursiondepthintheirqueryeitherthroughthequeryshapeortheconfigurationofthedatatype. |
| 77 | + |
| 78 | +###Complexity |
| 79 | + |
| 80 | +ForJSONEFonlydoesaconstantamountofworkforeachvaluereturnedbythe `Utf8Reader`,sameforeachvaluein `DbDataReader`. |
| 81 | + |
| 82 | +Somequeriescanproducea [cartesianexplosion](https://learn.microsoft.com/en-us/ef/core/querying/single-split-queries#cartesian-explosion) where the number of rows returned is the product of the number of rows the select from 2 or more tables. This can be mitigated by using `AsSplitQuery`. EF Core also produces a warning for this case as it's an issue in the user's code that can be easy to miss. |
| 83 | +
|
| 84 | +EFcreatesobjectsatlinearrelationtothedatareceived.TheamountofworkEFperformsisO(n)wherethenisthesizeofthedatabaseresponse. |
| 85 | + |
| 86 | +Forparticularlylargedatasetsstreamingorpagingcanbeusedtolimitthepeakamountofmemoryused. |
| 87 | + |
| 88 | +##Threats |
| 89 | + |
| 90 | +###Querypipeline/BulkCUD |
| 91 | + |
| 92 | +####SQLInjection |
| 93 | + |
| 94 | +MostEFqueriesarespecifiedusingLINQwhereuserinputissentasparameterswhicharenotvulnarabletoSQLinjection.Methodslike `ExecuteSql`and `FromSql`accepta `FormattableString`whichcanbeparameterizedaswell.However,themethods `FromSqlRaw`and `ExecuteSqlRaw`accepta `string`andifthedeveloperdirectlyconcatenatesuserinputtothesuppliedSQLcommandanattackercanprovidedatacontainingcommandsthatcanbeusedforSpoofing,Tampering,Repudiation,Informationdisclosure,DenialofserviceorElevationofprivilege. |
| 95 | + |
| 96 | +**Mitigation:**Thesemethodsaredocumentedaspotentiallydangerousandtheuserisresponsibleforinputsanitization. |
| 97 | + |
| 98 | +####JSONdeserializersDoS |
| 99 | + |
| 100 | +AnattackercaninjectmaliciousdatainthedatabasethatcausesDenialofservicefortheclientmachine. |
| 101 | + |
| 102 | +**Mitigation:**EFreliesontheunderlyingdatabaseanddrivertoavoidinjectionandthedevelopersareadvisedtonotdirectlyembeduntrustedJSONstringsinthedatabase.Butasdefenseindepth,EFdeserializerimplementationsusing `Utf8JsonReader`areO(n). |
| 103 | + |
| 104 | +####QuerycacheDoS |
| 105 | + |
| 106 | +InapplicationsthatbuildqueriesdynamicallyanattackercanprovidemaliciousdatathatcausesDenialofservicefortheclientmachinebybloatingthequerycache. |
| 107 | + |
| 108 | +**Mitigation:**Applications [buildingqueriesdynamically](https://learn.microsoft.com/ef/core/performance/advanced-performance-topics?%2Cexpression-api-with-constant#dynamically-constructed-queries) should restrict the ability of user input to affect the query shape to a reasonable degree that's appropriate for the application. As defense in depth EF computes the cache key in O(n) and query cache size is limited to 10240. Developers can call `UseMemoryCache` to provide an instance with a different size limit. Currently, the following sizes are used by the caching mechanism: |
| 109 | +
|
| 110 | +*Model - 250 |
| 111 | +*Compiledquery - 10 |
| 112 | +*Relationalquerycommand - 10 |
| 113 | + |
| 114 | +###Logging,interceptors,diagnostics |
| 115 | + |
| 116 | +####Informationdisclosure |
| 117 | + |
| 118 | +Ifthemechanismusedforlogging,interceptorsordiagnosticscrossesatrustboundaryanattackercanexploitavulnerabilitytocauseInformationdisclosureofthedatainqueriessenttothedatabase. |
| 119 | + |
| 120 | +**Mitigation:**BydefaultEFwon'tincludesensitiveinformationinthecalltologging,interceptorsordiagnostics.Here,sensitiveinformationisthedatathatwouldbesentasparameters.Namesofusertypes,databaseobjectsandconstantsusedinthequeriesarenotconsideredsensitive.EFprovidesastrictersensitivitylevelthatwillalsocensorconstants. |
| 121 | + |
| 122 | +###Modelbuilding |
| 123 | + |
| 124 | +Modelbuildingisbasedonstaticcodeintheloadedassemblyandisconsidertobetrusted. |
| 125 | + |
| 126 | +###TypeMapping |
| 127 | + |
| 128 | +AtypemappingisaninternalobjectthatprovidesinformationonhowaCLRtypemapstoatypenativelysupportedbythetargetdatabase. |
| 129 | + |
| 130 | +####Cachingconsiderations |
| 131 | + |
| 132 | +Typemappingscanbecalculatedrepeatedlyforparameterscontaininguserinputofdifferentlengths,soanattackercanusethistoartificiallybloatthetypemappingcacheuptoasetsizeandpotentiallycauseDenialofservicefortheclientmachine. |
| 133 | + |
| 134 | +Forexample,ifa `string`isprovidedbytheuserEFusesthelengthtodeterminewhetheritneedstobemappedtoSQLdatatypeofaspecificlength - `nvarchar(24)`orunbounded - `nvarchar(max)`.Byprovidingstringsofdifferentlengthstheuserwillcauseanewtypemappingtobecalculatedeachtime. |
| 135 | + |
| 136 | +**Mitigation:**EFwilluseadifferenttypemappingcachingmechanismforqueryparametersandgrouptypemappingsinthecachebasedonalimitednumberofvaluesforthelength. |
| 137 | + |
| 138 | +###Migrations |
| 139 | + |
| 140 | +####MigrationslockDoS |
| 141 | + |
| 142 | +Migrationapplicationcanhappenatruntimeandtakeadatabase-widelockthatcouldcausedelaysandpotentiallycauseDenialofservicefortheclientmachine.Forexample,theattackercouldspiketheloadfortheapplicationthatwouldcauseittoscaleout (ifconfigured)andthiscouldtriggermultipleconcurrentattemptstoapplythemigrations. |
| 143 | + |
| 144 | +**Mitigation:** [Theguidance](https://learn.microsoft.com/ef/core/managing-schemas/migrations/applying#apply-migrations-at-runtime) is to only perform migration application once per deployment. |
| 145 | +
|
| 146 | +####Migrationselevationofprivilige |
| 147 | + |
| 148 | +Migrationapplicationrequiresmorepermissionthanrequiredfornormalappoperation.Ifanattackerisablegaincontroloftheapporthecredentialstheywouldbeabletoinflictmoredamagethanotherwise. |
| 149 | + |
| 150 | +**Mitigation:** [Theguidance](https://learn.microsoft.com/ef/core/managing-schemas/migrations/applying#apply-migrations-at-runtime) is to use separate credentials for applying migrations that allow DDL operations and restrict them for the normal app execution. |
| 151 | +
|
| 152 | +###CLITools |
| 153 | + |
| 154 | +Thetoolsbuildandloadthedeveloper'sprojectcontainingthecontext,model-buildingcodeandmigrationsbeforerunninganyoperation.EFtoolsrelyonMSBuildtobuildthesupplytheexpectedassemblytoload. |
| 155 | + |
| 156 | +###Providers,Plug-ins |
| 157 | + |
| 158 | +EFextensibilityreliesonlyonstaticcodetoexplicitlyuseprovidersandplug-insthatcouldmodifytheruntimebehavior. |