OWASP Enterprise Security API (ESAPI) Zehra Saadet Öztürk Oksijen ARGE 9 Haziran 2012 1 12 June 2012
ESAPI nedir? > Web uygulamaları için güvenlik kontrol kütüphanesi > Güvenlik problemlerini gidermek için arayüzleri sağlar > Java,.Net, ASP, PHP, Phyton, Javascript,C, CPP sürümleri vardır > Ücretsiz, açık kaynak kodlu > BSD lisanslı 2 12 June 2012
Authenticator User AccessController AccessReferenceMap Validator Encoder HTTPUtilities Encryptor EncryptedProperties Randomizer Exception Handling Logger IntrusionDetector SecurityConfiguration ESAPI Custom Enterprise Web Application Enterprise Security API Existing Enterprise Security Services/Libraries 3 12 June 2012
ESAPI Girdi Doğrulama > White List Validation > Canonicalize > Intrusion Detection > Örnek metodlar > getvalidsafehtml > getvaliddate > getvalidnumber > getvalidfilecontent > getvalidfilename > getvalidcreditcard > isvalidfileupload > isvalidhttprequestparameterset 12 June 2012
ESAPI Girdi Doğrulama < Percent Encoding %3c %3C HTML Entity Encoding < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < &Lt < < < ≪ < JavaScript Escape \< \x3c \X3c \u003c \U003c \x3c \X3C \u003c \U003C CSS Escape \3c \03c \003c \0003c \00003c \3C \03C \003C \0003C \00003C Overlong UTF-8 %c0%bc %e0%80%bc %f0%80%80%bc %f8%80%80%80%bc %fc%80%80%80%80 %bc US-ASCII ¼ UTF-7 +ADw- Punycode <- 12 June 2012
ESAPI Girdi Doğrulama > getvalidinput > validation.properties > Validator.MSISDN=^(9054[0-9]{8} 9050[0-9]{8} 9053[0-9]{8} 9055[0-9]{8})$ > Validator.employeeID=^([A-Za-z0-9]{20,50})$ MyValidator +isvalidinput() +...() +isvalidemployeeid() Your implementation (has additional and/or perhaps changed functions compared to reference implementation) ESAPI interface «interface» Validator +isvalidinput() +...() May also be modified DefaultValidator +isvalidinput() +...() ESAPI reference implementation (does not include a isvalidemployeeid function) 12 June 2012
ESAPI Girdi Doğrulama - Örnek try { String cleanmarkup = ESAPI.validator().getValidSafeHTML( "htmlinput", htmlinput, 1000, true); String cleanmsisdn = ESAPI.validator().getValidInput( "msisdn:"+msisdninput, msisdninput, "MSISDN", 12, false); String cleanpassword = ESAPI.validator().getValidInput( "pwd:" + pwdinput, pwdinput, "pwdwhitelist", 15, true); } catch (ValidationException e) { logger.error("[validation Failed]" + e.getmessage()); } catch (IntrusionException e) { logger.error("[intrusion] " + e.getmessage()); } 12 June 2012
ESAPI Çıktı Kodlama (Output Encoding) > Çıktı Kodlaması yaparken... > Hedef Yorumlayıcı & doğru kodlama metodu > Hangi karakterler? > Double encoding! > encodeforjavascript(string input) > encodeforhtml(string input) > encodeforcss(string input) > encodeforldap(string input) > encodeforxpath(string input) > encodeforxml(string input) > String canonicalize(string input) 12 June 2012
ESAPI Çıktı kodlama Örnek: XSS Rule #0 : Never Insert Untrusted Data Except Allowed Locations Rule #1: HTML escape in HTML Element Content ESAPI.encoder.encodeForHTML(input) Rule #2: Atribute escape in HTML Common Attributes ESAPI.encoder.encodeForHTMLAttribute(input) Rule #3: Javascript Escape in HTML Javascript Data Values ESAPI.encoder.encodeForJavaScript(input) Rule #4: CSS Escape HTML Style Property Values ESAPI.encoder.encodeForCSS(input) Rule #5: URL Escape HTML URL Attributes ESAPI.encoder.encodeForURL(input) 12 June 2012
ESAPI Çıktı kodlama XSS <script> x=<%=request.getparameter( "input")%> </script> <Table> <TR> <TD>Full Name:</TD> <TD><%=user.getFirstName()%> <%=user.getlastname()%></td> <TD> <a href= sendmessage?userid= <%=user.getid()%> >Send Message</a> </TD> <script> x=<%=esapi.encoder().encodeforjavascript( request.getparameter( "input"))%> </script> <Table><TR> <TD> Full Name:</TD> <TD> <%=ESAPI.encodeForHTML( user.getfirstname())%> <%= ESAPI.encodeForHTML( user.getlastname())%></td> <TD><a href= sendmessage?userid= <%=ESAPI.encoder().encodeFor URL(user.getId()%>) >Send Message</a> </TD> 12 June 2012
ESAPI Kodlama Örnek: SQL Injection > encodeforsql tavsiye edilmeyen bir yöntem > Asıl yapılması gereken PreparedStatement kullanmak String query = "SELECT account_balance FROM user_data WHERE user_name = " + request.getparameter("customername"); String query = "SELECT account_balance FROM user_data WHERE user_name = " + ESAPI.encoder().encodeForSQL(new OracleCodec(),request.getParameter("customerName")); 11 12 June 2012
Kullanıcı Doğrulama (Authentication) > ESAPI.properties ESAPI.Authenticator=org.owasp.esapi.reference.FileBasedAuthenticator ESAPI.Authenticator=com.vodafone.myapp.auth.MyAuthenticator MyAuthenticator +login() +...() Your implementation (has the same functions as reference implementation) ESAPI interface «interface» Authenticator +login() +...() DefaultAuthenticator +login() +...() ESAPI reference implementation 12 12 June 2012
Kullanıcı Doğrulama (Authentication) > Kullanıcı yaratma Kullanıcı adı ve şifre güçlülüğünü sınama Password hash (sha2 hash & username salt ) User user = ESAPI.authenticator().createUser("saadet", "Password1?", "Password1?"); 13 12 June 2012
Kullanıcı Doğrulama (Authentication) > Login Ip değişikliği yakalama Session Id değiştirilmesi Fazla denemede hesap kilitleme Beni hatırla not POST, non-ssl User user = ESAPI.authenticator().login(httpServletRequest, httpservletresponse); 14 12 June 2012
Kullanıcı Doğrulama (Authentication) ESAPI.authenticator().getUser("saadet").lock(); ESAPI.authenticator().getUser("saadet").disable(); ESAPI.authenticator().verifyPasswordStrength("oldP assword", "newpassword", ESAPI.authenticator().getUser("saadet")); 15 12 June 2012
Erişim Kontrolleri (Access Control) > assertauthorizedforurl(java.lang.string url) > assertauthorizedforfunction(java.lang.string functionname) > assertauthorizedforservice(java.lang.string servicename) > Indirect Object reference RandomAccessReferenceMap 16 12 June 2012
Erişim Kontrolleri (Access Control) URLAccessRules.txt /MyApp/userList.action any allow /MyApp/userEdit.action admin allow /MyApp/userDelete.action standart deny try { ESAPI.accessController().assertAuthorizedForURL( request.getrequesturi()); return actioninvocation.invoke(); } catch (AccessControlException e) { logger.info(null, "[AuthorizationInterceptor] User is not authorized for url:" + request.getrequesturi()); } return AUTH_FAILURE; 17 12 June 2012
ESAPI ve CSRF( Cross Site Request Forgery) > Linke CSRF token ekleme > <a href='<%=esapi.httputilities().addcsrftoken( /myapp )%> ' target="_blank">transfer Funds</a> > Linke tıklandığında CSRF token doğrulama try { ESAPI.httpUtilities().verifyCSRFToken(); logger.debug("csrf Token Validated "); } catch (IntrusionException e) { } logger.fatal(logger.security_failure, "[Intrusion] CSRF Token Not Validated "+e.getlogmessage()); return e.getusermessage(); 18 12 June 2012
Oturum Yönetimi > Oturum Sabitleme (Session Fixation) Zaafiyeti > Oturum anahtarının saldırgan tarafından kullanıcıya kabul ettirilmesi > ESAPI.httpUtilities().changeSessionIdentifier() 19 12 June 2012
ESAPI Kriptorafi Encryptor Interface > String hash(string plaintext, String salt) (sha-2) > CipherText encrypt(secretkey key, PlainText plain) > CipherText encrypt(plaintext plain) ( Masterkey in ESAPI.prop) > PlainText decrypt(ciphertext ciphertext) > PlainText decrypt(secretkey key, CipherText ciphertext) > String seal(java.lang.string data, long timestamp) > String unseal(java.lang.string seal) > boolean verifyseal(java.lang.string seal) 20 ESAPI 12 June 2012
ESAPI Kriptorafi Randomizer Interface > boolean getrandomboolean() > String getrandomfilename(string extension) > String getrandomguid() > int getrandominteger(int min, int max) > long getrandomlong() > loat getrandomreal(float min, float max) > String getrandomstring(int length, char[] characterset) 21 12 June 2012
ESAPI Loglama > Etiketleme mekanizması: SECURITY_SUCCESS, SECURITY_FAILURE, EVENT_SUCCESS, EVENT_FAILURE > Encode CRLF > Encode HTML characters > Log4JLogFactory, JavaLogFactory private static final Logger logger = ESAPI.getLogger(TransferFunds.class); logger.fatal(logger.security_failure, "[Intrusion] CSRF Token Not Validated "+e.getlogmessage()); 22 12 June 2012
ESAPI HTTP Utilities > ESAPI.httpUtilities().setNoCacheHeaders() > Reader.readLine() -> Validator.safeReadLine() > Math.Random.* -> Randomizer.* > ServletResponse.setContentType() -> HTTPUtilities.setContentType() > ServletResponse.sendRedirect() -> HTTPUtilities.sendSafeRedirect() > RequestDispatcher.forward() -> HTTPUtilities.sendSafeForward() > ServletResponse.addHeader() -> HTTPUtilities.addSafeHeader() > ServletResponse.addCookie() -> HTTPUtilities.addSafeCookie() > ServletRequest.isSecure() -> HTTPUtilties.isSecureChannel() > ServletResponse.encodeURL -> HTTPUtilities.safeEncodeURL (better not to use at all) > ServletResponse.encodeRedirectURL -> HTTPUtilities.safeEncodeRedirectURL (better not to use at all) > java.security and javax.crypto -> Encryptor.* > java.net.urlencoder/decoder -> Encoder.encodeForURL/decodeForURL 23 12 June 2012
ESAPI Swingset
? 25 12 June 2012
Teşekkürler... 26 12 June 2012
ESAPI Girdi Doğrulama > getvalidsafehtml(string context, String input, int maxlength, boolean allownull) > getvaliddate(string context, String input, java.text.dateformat format, boolean allownull) > getvalidnumber(string context, String input, long minvalue, long maxvalue, boolean allownull) > getvalidfilecontent(string context, byte[] input, int maxbytes, boolean allownull) > getvalidfilename(string context, String input, boolean allownull) > boolean getvalidcreditcard(string context, String input, boolean allownull) > isvalidfileupload(string context, String filepath, String filename, byte[] content, int maxbytes, boolean allownull) > isvalidhttprequestparameterset(string context, Set required, Set optional)
ESAPI Girdi & Çıktı Denetimi User Controller Business Functions Data Layer Backend getvalidcreditcard getvaliddirectorypath getvalidfilecontent getvalidfilename getvalidinput getvaliddirectorypath getvalidredirectlocation getvaliddate getvalidprintable safereadline encodeforjavascript encodeforvbscript Validator Encoder encodeforurl Canonicalization Double Encoding Protection Sanitization Normalization encodeforhtml encodeforhtmlattribute encodeforldap encodefordn encodeforsql encodeforxml encodeforxmlattribute encodeforxpath