Presentation laddar. Vänta.

Presentation laddar. Vänta.

Säkerhet för utvecklare

Liknande presentationer


En presentation över ämnet: "Säkerhet för utvecklare"— Presentationens avskrift:

1 Säkerhet för utvecklare
Johan Lindfors Senior Developer Evangelist Microsoft AB 2006 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.

2 12 råd som bör följas Anamma ”Least Privilege”
Skriv applikationer för icke-adminstratörer Kräv inte ”sa”-rättigheter Lita aldrig på inmatning från användare Förhindra XSS Skydda dig mot ”Buffer Overruns”

3 12 råd som bör följas Se över din krypteringskod
Minska exponeringsytan Hantera fel på korrekt sätt Var försiktig med ”Impersonation” Försök använda ”hanterad kod” och sist men absolut inte minst… Kontinuerlig utbildning är nyckeln!!!

4 ”Least privilege” (1, 2) Applikationer bör exekvera med minsta rättigheter Då bör du också utveckla med de rättigheterna Visual Studio 2005 använder inte ”Debugger Users” längre Fångar fel tidigare i processen Högre kvalitet på produkten Passar som handsken i SDL 2006 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.

5 Utveckla utan administrativa rättigheter
Exekvera, debugga, runas 2006 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.

6 Konsekvenser av inmatning (4)
Hantering av inmatning ska alltid ske Kan nämligen leda till… SQL Injection Cross-Site Scripting (XSS) “One-Click Attacks” “Canonicalization” utmaningar Felaktiga minnesadresseringar

7 Skydd mot ”SQL Injection” (9)
Använd inte dynamisk SQL Använd lagrade procedurer eller parameteriserade SQL frågor Sanera all inmatning Betrakta all inmatning som skadlig Testa för korrekt data och förkasta allt annat Exekvera med minsta rättigheter, inte “sa” Begränsa åtkomst till inbyggda procedurer Visa inte ODBC felmeddelanden Input character Meaning in Transact-SQL ; Query delimiter ‘ Character data string delimiter Comment delimiter /* ... */ Comment delimiters. Text between /* and */ is not evaluated by the server. Xp_ Begins the name of catalog extended stored procedures such as xp_cmdshell. 2006 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.

8 Skydd mot ”XSS” (5) Dåligt: Bra: Lita på inmatning från användare
”Eka” klientens data utan att ”koda” Lagra hemlig information i “cookies” Bra: Utnyttja ASP.NET: RequestValidation Utnyttja ASP.NET: ViewStateUserKey Använd IOSec för kodning av data Input validation First line of defense – can eliminate many possible vulnerabilities, but doesn’t necessarily eliminate all of them Output encoding By encoding user-supplied data at display time, we can ensure that the client browser will interpret it literally Platform features RequestValidation property ViewStateUserKey property Server.HtmlEncode() doesn’t always protect your app… It only encodes < > & “ Use IOSec (properly implemented) EncodeHtml() EncodeHtmlAttribute() EncodeVbs() EncodeJs() AsUrl() 2006 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.

9 Skydd mot felaktig inmatning
Exekvera, debugga, runas 2006 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.

10 Förbättringar för C++ (6)
”Buffer Overruns” är fortfarande vanligt! ”C Runtime” designades långt innan vi tänkte på säkerhet Ett flertal av utmaningarna i dag relaterar till användningen av ”C Runtime” Vi har gjort en del förändingar i och med Visual Studio 2005 “Safe CRT” initiativet Har lämnats in för standardisering Kräver dock kodförändringar!

11 C++ och utmaningar Exekvera, debugga, runas
2006 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.

12 Säkerhet och .NET Fx (8, 11) Kod och bevisbaserad säkerhet
Minskar kodens åtkomst till skyddade resurser Rättigheter representerar åtkomst till resurser Adminstratörer kan konfigurera inställningar Kod kan begära rättigheter Och specificera rättigheter som absolut inte behövs Ger kod möjligheten att kräva att anropande kod har vissa rättigheter eller signaturer

13 Regelverk för säkerhet Utvärdering mot regler
Hur fungerar det? Assembly A3 Värd Bevis “Permission Requests” Regelverk för säkerhet Assembly A2 G2 G1 Assembly A1 Utvärdering mot regler G3 Assembly A3 G3

14 Imperativ säkerhetskontroll
MGB 2003 Imperativ säkerhetskontroll Exempel FileIOPermission filePerm = new FileIOPermission( FileIOPermissionAccess.Read, "C:\\temp.txt"); try { filePerm.Demand(); // Kod för att jobba mot filen här } catch (SecurityException e) // detta exekveras om åtkomsten vägras Expressing security requirements in the Imperative style means creating instances of Permisson objects at run time and invoking methods on them. The above code creates an instance of a FileIOPermission object that represents the right to read the file C:\temp.txt. If the call to the Demand method succeeds, execution continues after the call. Otherwise, a SecurityException is thrown. At any point, an assembly can request a permission using a suitable permission object. The code above is making a request to access the file c:\temp.txt. Note that this request will be granted on evidence that the runtime obtains. For example, if the runtime finds that the code belongs to the code group ‘Programmers’ and programmer’s have insufficient permissions, the request to access the file will be declined. Whilst obtaining evidence, the runtime will walk the stack, assuring that less privileged code further up the stack tree is not trying to execute code that it itself should not normally have access to. Imperative security checking requires the developer to create a permission based object, and then make a call to a method such as Demand at runtime. In some scenarios, this may not be appropriate. For example, you may want the runtime to evaluate the code at load time. In such cases, a developer may chose to use declarative security checking. Exekveringsmotorn kommer att “gå i stacken” och kontrollera att all kod har korrekta rättigheter, om inte så kastas ett “SecurityException” 2006 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary. © 2003 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary. 14

15 Deklarativ säkerhetskontroll
MGB 2003 Deklarativ säkerhetskontroll Använd attribut för att genomföra säkerhetskontroller Fel genererar “SecurityException” Deklarativ säkerhet lagras som metadata Enklare genomgång av kod [FileIOPermission(SecurityAction.Demand, Read= "C:\\temp.txt")] public string ReadTempFile() { // Kod för att läsa filen här } Expressing security constraints in the Declarative style means using the custom attribute syntax. These annotations are persisted in the metadata for the type, effectively being baked into the assembly at compile time. You can also use declarative security syntax to demand permissions. Declarative security syntax uses attributes to specify permission requests. You can use attributes on methods or entire classes. Declarative security syntax makes it easier for testers and code auditors to review code. Tools such as the Permission Review Tool use declarative security syntax to document security requirements. Declarative security is not as flexible as imperative security as it only allows attributes to be specified at the method or assembly level 2006 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary. © 2003 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary. 15

16 ”Permission Requests”
MGB 2003 ”Permission Requests” Utvecklaren lägger till önskade rättigheter till en assembly med hjälp av attribut 3 typer av begäran: Ger en mekanism som: Tillåter en assembly att kräva rättigheter Förhindrar att en assembly laddas om inte dess krav är uppfyllda Minimum “Optional” “Refused” Developers use permission requests to state the permission requirements of their assemblies. Using permission requests makes it easier to run code with least privilege. If an assembly does not receive its minimum permission request, it does not load. For example. Imagine that you are using a text editor. After about 20 minutes of typing you hit the save button. The application responds with an error message stating that you do not have the necessary security rights to write to the disk drive. It would have been much nicer if you have been told up front that the application would not be able to write to disk – saving you 20 minutes of your time. Using permission requests, a .NET application can specify up front what security rights it requires. In this example the text editor could have been coded in such a way that it specified it’s required security needs. The .NET runtime could then make a decision to run the application or not at load time. 2006 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary. © 2003 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary. 16

17 MGB 2003 Exempel på begäran // Jag kommer bara att köra om jag får anropa ohanterad kod [assembly:SecurityPermission( SecurityAction.RequestMinimum, UnmanagedCode=true)] // Jag måste ha rättigheter som i “FullTrust PermissionSet” [assembly:PermissionSet( SecurityAction.RequestMinimum, Name="FullTrust")] // Bara kod som signerats med 12789ADE...kan anropa mig [StrongNameIdentityPermission(SecurityAction.LinkDemand PublicKey = "12789ADE…", Version = " ")] public class MyClass { // MyClass can only be called by the assembly // with the strong name specified in the attribute } The first code sample adds a minimum permission request for the right to call unmanaged code to the assembly. The second code sample adds a minimum permission request for all permissions (FullTrust) to the assembly. You can put as many permission-request attributes as you need in your code 2006 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary. © 2003 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary. 17

18 Kod och bevisbaserad säkerhet
Exekvera, debugga, runas 2006 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.

19 “Stack Walk” Assembly A PermissionSet Assembly B PermissionSet
Assembly C PermissionSet Assembly D PermissionSet “Stack walk” för rättigheten p P.Demand() Exempel på “Stack walk”

20 ”Stack Walk” Exekvera, debugga, runas
2006 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.

21 Identiteter och ”principals”
MGB 2003 Identiteter och ”principals” En identitet innehåller information om en användare, till exempel inloggningsnamn En “principal” innehåller rollinformation om en användare eller dator Generisk Windows Skräddarsydd An identity contains information about the user’s identity, such as logon name and whether the user is authenticated. A principal contains information about role membership. The .NET Framework implements two major types of identities and principals. WindowsIdentity and WindowsPrincipal objects provide information about the Windows credentials for a user. GenericIdentity and GenericPrincipal objects allow the developer to implement their own authentication technique. 2006 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary. © 2003 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary. 21

22 MGB 2003 Identiteter i Windows Använd objekten WindowsIdentity och WindowsPrincipal för: Enstaka validering Repeterade valideringar WindowsIdentity myIdent = WindowsIdentity.GetCurrent(); WindowsPrincipal myPrin = new WindowsPrincipal(myIdent); AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal); WindowsPrincipal myPrin = System.Threading.Thread.CurrentPrincipal; The first code sample is more efficient if the principal and identity are retrieved just once, and the second sample is more efficient if the principal and identity are retrieved multiple times. 2006 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary. © 2003 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary. 22

23 Generiska identiteter
MGB 2003 Generiska identiteter Skapa “GenericIdentity” och “GenericPrincipal” Lägg till “GenericPrincipal” till aktuell tråd “GenericPrincipal” kommer att användas vid framtida säkerhetskontroller på tråden GenericIdentity myIdent = new GenericIdentity("User1"); string[] roles = {"Manager", "Teller"}; GenericPrincipal myPrin = new GenericPrincipal(myIdent, roles); Creating GenericIdentity and GenericPrincipal objects is useful when you want to implement custom authentication techniques, such as when you want to find credentials in a database. This also makes role-based security easier, because you can still use the standard .NET Framework techniques to perform security checks. You do not have to write different code to perform the checks if you implement custom authentication. System.Threading.Thread.CurrentPrincipal = myPrin; 2006 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary. © 2003 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary. 23

24 Rollbaserade kontroller (1/2)
MGB 2003 Rollbaserade kontroller (1/2) Använd egenskapen “Name” på “ID” objektet för att kontrollera inloggningsnamn Använd metoden “IsInRole” på “P” objektet för att kontrollera medlemskap i roller if (String.Compare(myPrin.Identity.Name, "DOMAIN\\Fred“,true)==0) { // Permit access to some code } The first code sample performs a case-insensitive string comparison of the current identity’s Name property and a hard-coded string. The second code sample uses the IsInRole method to check role membership. In this example the code checks the built in Administrators group. if (myPrin.IsInRole("BUILTIN\\Administrators")) { // Permit access to some code } 2006 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary. © 2003 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary. 24

25 Rollbaserade kontroller (2/2)
MGB 2003 Rollbaserade kontroller (2/2) Använd rättigheter för att kontrollera rollbaserade säkerhetskontroller Imperativt Deklarativt PrincipalPermission prinPerm = new PrincipalPermission("Teller", “Manager”, true); try { prinPerm.Demand(); // Matchar ovanstående aktiv “principal” } You can also use permission syntax to make role-based security checks. The first code sample uses imperative security syntax, and the second code sample uses declarative security syntax. Performing a demand does not cause a stack walk. Rather, the credentials on the current thread are checked. [PrincipalPermission(SecurityAction.Demand, Role="Teller", Authenticated=true)] 2006 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary. © 2003 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary. 25

26 Identiter och roller Exekvera, debugga, runas
2006 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.

27 Nyheter i .NET 2.0 (7) Transparens Enkelt API för “Sandboxing”
ClickOnce och PermCalc Starkare nycklar för SN “Full trust” i GAC CAS kan inte stängas av permanent Kryptering av XML Och en hel del till… and follow links Transparens Voluntarily gives up its ability to elevate the permissions of the call stack; That means that the following rules apply Cannot Assert for permissions to stop the stack walk from continuing It cannot satisfy a LinkDemand Cannot automatically use unverifiable code, even if it has SkipVerification permission Runs with either the set of permissions it has granted or the set of permissions its callers were granted Sandboxing med hjälp av ett nytt api: AppDomain.CreateDomain( string friendlyName,                         Evidence securityInfo,                         AppDomainSetup info,                         PermissionSet grantSet,                         params StrongName[] fullTrustAssemblies ); Support for larger SN keys Enhanced SecurityException Managed ACLs PKCS7 support FIPS enforcement RFC 2898 PBKDF 2 Test key signing Enhanced X509 support (via X509Certificate2) XML Encryption AppDomainManager/HostSecurityManager 2006 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.

28 Verktyg för utvecklare
Authorization Manager Varför bygga egna auktoriseringssätt Administrationsverktyg och modell Application Blocks Enterprise Library 2.0 Visual Studio Team System Statisk och dynamisk kodanalys Enhetstestning Last och stresstester Analys och rapportering

29 Verktyg för utvecklare
Exekvera, debugga, runas 2006 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.

30 Säkerhet i WCF Enhetlig programmeringsmodell Interoperabilitet
Mellan processer, datorer, domäner… .NET Framework baserad Interoperabilitet Baserat på WS-* specifikationerna Kompatibilitet med existerande säkerhetstekniker (Windows, Kerberos, X.509, HTTPS) Säker som grundinställning Alla ”standard” bindningar är säkra BasicHttpBinding är ett undantag!!!

31 Windows Communication Foundation
Exekvera, debugga, runas 2006 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.

32 Windows CardSpace “Relying Party” “Identity Provider” Användare

33 Windows CardSpace Exekvera, debugga, runas
2006 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.

34 Kort paus för omstart!

35 ”User Account Control” (1)
Alla interaktiva processer exekverar som en vanlig användare Tillåtelse från användaren krävs för att begära ytterligare rättigheter En speciell ikon identifierar operationer som kräver ytterligare rättigheter 2006 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary. 35

36 Påverkan på applikationer
Virtualisering av registret och filsystemet %userprofile%\AppData\Local\VirtualStore HKEY_CURRENT_USER\Software\Classes\VirtualStore Virtualisering är en kompatibilitets-funktion för existerande applikationer Nya och uppdaterade applikationer ska inte förlita sig på virtualisering! Windows Vista applikationer bör i ett “manifest” begära rättigheter 2006 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary. 36

37 Stänga av UAC istället? Absolut inte, det är steg vi behöver ta!
Utbilda dig själv och ditt företag Vi kommer att fortsätta göra detta ”sexigare” Skydda dina användare och kunder

38 5 steg till kompatibilitet
Bedöm om din applikation redan exekverar som “standard user” Identifiera operationer som kräver ytterligare rättigheter Adressera identifierade operationer, om möjligt Markera dina applikationer som UAC-benägna Adressera operationer som kräver ytterligare rättigheter

39 Hitta priviligerade operationer
Använd verktyget “Standard User Analyzer” Identifierar operationer som kommer att kräva ytterligare rättigheter Kan användas på Windows XP Konfigurera maskinspecifika inställningar vid installation, hellre än vid första starten Ändra maskinspecifika inställningar till användarspecifika om möjligt

40 Markera din applikation för UAC
Erbjud ett manifest (en XML-fil) Ett manifest är en XML-fil med namnet: <exeNamn>.exe.manifest Sätt elementet <requestedExecutionLevel/> Vanligtvis till “asInvoker” Detta stänger också av virtualiseringen Manifest kan vara externa eller “embedded” Externa manifest hittas i samma katalog som den exekverbara filen “Embedded” manifest inkluderas som en ren Win32 resurs Logo requirement Every executable file (with a .exe extension) included with an application must have an embedded manifest that defines its execution level 2006 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary. 40

41 Skapa ett manifest Lägg till en XML-fil till projektet
Byt namnet till <appName>.exe.manifest <?xml version="1.0" encoding="utf-8" ?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1” manifestVersion="1.0"> <assemblyIdentity version=" " processorArchitecture="X86" name="AppName" type="win32" /> <description>App Description</description> <trustInfo xmlns="urn:schemas-microsoft.com:asm.v3"> <security> <requestedPrivileges> <requestedExecutionLevel level="asInvoker" /> </requestedPrivileges> </security> </trustInfo> </assembly> requestedExecutionLevel requireAdministrator highestAvailable asInvoker 2006 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary. 41

42 ”Embedded” manifest Lägg till en resursfil till projektet (text-fil) och byt namn till <appName>.rc Lägg till en kompileringshändelse “pre-build” “<path to SDK>\rc.exe” $(ProjectDir)$(ProjectName).rc Lägg till Win32-resursen till “assembly” #define RT_MANIFEST 24 #define APP_MANIFEST 1 APP_MANIFEST RT_MANIFEST <appName>.exe.manifest <PropertyGroup> <Win32Resource>appName.res</Win32Resource> </PropertyGroup> 2006 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary. 42

43 Adressera viktiga operationer
Överväg andra nivåer på <requestedExecutionLevel/> requireAdministrator eller highestAvailable Vissa applikationer kräver rättigheter för en liten del av sin funktionalitet Priviligerade rättigheter måste ges till en egen process Kräver “refactoring” till separata paritioner Gränssnittet bör dekoreras med skölden Priviligerade partitioner måste startas antingen med ”ShellExecute” eller “COM elevation moniker”

44 Starta med ”ShellExecute”
Process proc = new Process(); proc.StartInfo = new ProcessStartInfo(); proc.StartInfo.CreateNoWindow = true; proc.StartInfo.UseShellExecute = true; proc.StartInfo.FileName = "PrivilegedExe.exe"; proc.EnableRaisingEvents = true; proc.Exited += new EventHandler(OnExeExited); proc.Start(); OBS: CreateProcess kan inte begära ytterligare rättigheter Visual Studio 2005 kan alltså inte automatiskt hantera detta!

45 Gör en applikation klar för UAC
Exekvera, debugga, runas 2006 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.

46 Bakåtkompatibilitet Vad händer om du kör en UAC-kompatibel applikation på Windows XP? <requestedExecutionLevel/> ignoreras Alla processer exekverar med de högsta tillgängliga rättigheterna Strategi för att försäkra sig om att partitionerade applikationer fortsätter att fungera på Windows XP Testa alltid tillgången till rättigheter vid uppstart (IsUserAdmin) och avsluta graciöst i de fall som denna nivå inte finns 2006 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary. 46

47 Checklista för utvecklare (12)
Utveckla inte som adminstratörer RunAs är ett bra komplement Validera all inmatning Se över era datalager Byt till hanterad kod Använd automatiska verktyg Förbered er för UAC Utbilda er kontinuerligt ”Writing Secure Code”

48 johan.lindfors@microsoft.com www.microsoft.se/partner/education
2006 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.


Ladda ner ppt "Säkerhet för utvecklare"

Liknande presentationer


Google-annonser