#sameorigin
Explore tagged Tumblr posts
pentesttestingcorp · 6 months ago
Text
Protect Your Laravel Application from Clickjacking Attacks
In today's digital landscape, protecting your web application from various security threats is crucial. One such threat is Clickjacking, an attack that tricks users into clicking on invisible or disguised elements on a webpage. For developers using the Laravel framework, ensuring your application is safe from clickjacking is essential.
Tumblr media
In this post, we'll explore what clickjacking is and how to prevent it in your Laravel application. Plus, we’ll show you how to use our free Website Security Checker tool to assess potential vulnerabilities.
What is Clickjacking?
Clickjacking is a type of attack where malicious users embed your webpage into an invisible iframe on their site. The attacker then tricks the victim into clicking on the iframe, which can lead to unwanted actions like changing settings, submitting forms, or even transferring funds without their knowledge.
For example, a button that looks harmless on the surface might trigger an action you didn’t intend to take when clicked in an iframe. This type of attack can be devastating for your users’ privacy and your application’s security.
Preventing Clickjacking in Laravel
Fortunately, Laravel provides a straightforward way to mitigate the risk of clickjacking. Here's how you can do it:
Step 1: Use HTTP Headers
The best way to prevent clickjacking in your Laravel application is by setting proper HTTP headers. You can do this by adding the X-Frame-Options header to your application's response. This header tells the browser not to allow your webpage to be embedded in an iframe.
In Laravel, you can add this header globally by modifying the app/Http/Middleware/VerifyCsrfToken.php file.
Here’s how you can modify the middleware:
// app/Http/Middleware/VerifyCsrfToken.php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; class VerifyCsrfToken { public function handle(Request $request, Closure $next) { // Adding X-Frame-Options header to prevent clickjacking response()->headers->set('X-Frame-Options', 'DENY'); return $next($request); } }
With this code, the header X-Frame-Options: DENY ensures that no website can embed your pages in an iframe. If you want to allow only certain websites to embed your content, you can use SAMEORIGIN instead of DENY.
Step 2: Use Content Security Policy (CSP)
Another robust method to prevent clickjacking attacks is by using a Content Security Policy (CSP). Laravel supports CSP through middleware. By setting a strict policy, you can specify exactly which websites are allowed to load your pages in an iframe.
Here’s an example of how you can configure the CSP in your Laravel application:
// app/Http/Middleware/ContentSecurityPolicy.php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; class ContentSecurityPolicy { public function handle(Request $request, Closure $next) { // Setting a strict CSP header response()->headers->set('Content-Security-Policy', "frame-ancestors 'none';"); return $next($request); } }
This ensures that no site can embed your application within an iframe.
Why Use Our Free Website Security Checker?
After implementing these preventive measures, it’s important to test your application’s security. Our free Website Security Scanner tool provides a comprehensive vulnerability assessment for your website, including tests for clickjacking and other security issues.
Here’s a screenshot of our free tool in action:
Tumblr media
Screenshot of the free tools webpage where you can access security assessment tools.
Conclusion
Securing your Laravel application against clickjacking attacks is crucial for protecting your users and ensuring your web app remains safe. By following the steps outlined above, you can significantly reduce the risk of such attacks. Additionally, our free Website Security Checker can help you ensure that your site is not vulnerable to clickjacking or any other security issues.
And here’s an example of the vulnerability assessment report generated by our free tool:
Tumblr media
An example of a vulnerability assessment report generated with our free tool provides insights into possible vulnerabilities.
By regularly using security tools and following best practices, you can enhance your website’s defenses and maintain a safe browsing environment for your users.
Take Action Today
Start testing your website with our free tool to test website security free and take the first step in protecting your site from clickjacking and other cyber threats.
3 notes · View notes
kozba · 1 year ago
Text
CyberPanel'de Security Headers'ı Openlitespeed üzerinden optimize etmek oldukça kolaydır. Aşağıdaki adımları takip ederek Security Headers'ı kolayca optimize edebilirsiniz. Cyberpanel Kurulumu için ilgili bağlantıyı takip edebilirsiniz. Security Headers Nedir? HTTP Security Header, web sitenizin içeriğini tarayıcılara bildirmek ve tarayıcıların nasıl davranacağını belirtmek için kullanılır. SEO için de tercih edilen bir ayardır. Security Headers Check Openlitespeed Web Paneline giriş yapın. (Genellikle :7080 portudur.) Virtual Host'a giriş yapın. Security Headers eklemek istediğiniz sitenin olduğu alanda büyüteçe tıklayın. Context alanına gelin. Sağdaki + butonuna tıklayın. Type Static olacak, Devam butonuna tıklayın. URI = / Location = $DOC_ROOT Accessible = Yes Header Operations; Strict-Transport-Security: max-age=31536000; includeSubDomains Content-Security-Policy "upgrade-insecure-requests;connect-src *" Referrer-Policy strict-origin-when-cross-origin X-Frame-Options: SAMEORIGIN X-Content-Type-Options: nosniff X-XSS-Protection 1;mode=block Permissions-Policy: geolocation=(self "") Kaydet butonuna tıklayın. Ardından da Gracefull Restart butonuna tıklayın. Check için: Tıkla
0 notes
ryanvgates · 7 years ago
Text
No IFrame For You
No IFrame For You
Security isn’t easy, but its becoming more important. There’s lots of evidence explaining the dangers of missing any flaws. One of the items that got flagged on a project that allowed IFrames from any other site. The findings referenced the X-Frame-Options header. In my particular case, the business wanted to allow IFraming across domains. This ruled out using DENY or SAMEORIGIN. ALLOW-FROM would…
View On WordPress
0 notes
hackgit · 3 years ago
Text
[Media] ​​HTTPHeaderBrowserTesting
​​HTTPHeaderBrowserTesting This is the source code of an automated service (reachable under https://much.ninja) that allows you to test your browser behavior regarding header enforcement and duplicated headers and conflicting directives. Duplicated headers are multiple headers with the same name in a HTTP response: X-Frame-Options: deny X-Frame-Options: sameorigin An example for conflicting directives within a header would be: X-Frame-Options: deny, sameorigin We also test what happens, if the browser encounters invalid directives or invalid header values: X-Frame-Options: random, deny or Strict-Transport-Security: max-age: 60, includeSubdomains (a comma is used as separator) In particular, we test the following headers: ▫️ Duplicated X-Frame-Options (XFO) headers and conflicting directives ▫️ X-Frame-Options via meta tag ▫️ Content-Security-Policy (CSP) frame-ancestors ▫️ Content-Security-Policy frame-ancestors via meta tag ▫️ X-Frame-Options and Content-Security-Policy frame-ancestors (both set) ▫️ Duplicated Strict-Transport-Security (HSTS) headers and conflicting directives ▫️ Duplicated CORS headers and conflicting directives (SOP subset XMLHttpRequest) https://github.com/hen95/HTTPHeaderBrowserTesting
Tumblr media
0 notes
ethical-hacking · 5 years ago
Text
Chapter 01. 웹과 HTTP 기초
Tumblr media
이 카테고리는 본인이 완주한
"화이트 해커를 위한 웹 해킹의 기술"이라는
책으로 공부한 내용을 복습 겸 게시할 계획입니다.
웹 해킹 사이트에서 직접 실습을 할 수 있고,
무료로 강의를 제공해서무리(?) 없이 학습을 해갔었다
웹 아키텍처
1.클라이언트 영역
1.1 프레젠테이션 티어
2.서버 영역
2.1 로직 티어: HTTP 요청 처리 및 응답(ex: 웹 서버와 웹 프레임워크)
2.2 데이터 티어: 데이터 처리 및 결과 응답(ex: DBMS, DB)
HTTP 요청 메시지
1.요청 메세지의 구성
1.1 <바디>를 통해 데이터가 전송됨
1.2 데이터를 전송할 필요가 없는 경우에는 <바디> 부분 없이 구성
//헤더와 바디가 구분될 때 빈 줄에 줄 바꿈을 위해 CRLFCRLF 사용되는데,
CRLF를 강제로 전송하여 의도치 않은 결과를 초래하도록 만든것-> CRLF 인젝션, HTTP 응답 스플리팅
2. 메소드
- 서버에게 어떤 명령을 실행할지 알려주는 역할
2.1 GET: 지정된 리소스를 요청
2.2 POST: 클라이언트 쪽에서 데이터를 서버 쪽으로 전달
2.3 PUT: 지정된 리소스에 데이터를 저장
2.4 DELETE: 지정된 리소스를 ���제
2.5 HEAD, OPTIONS…
3. 요청 URI
- 요청이 파라미터르 전달하는 경우에는 ?가 사용됨
(ex: /sqli/?id=1&Submit=Submit)
4. 요청 헤더
Tumblr media
이미지출처: https://mer-bleu.tistory.com/13
-헤더는 리스트의 형태로 여러 개 전송 가능
헤더이름: 헤더 값
5.헤더 예제
5.1 HOST
- 서버의 도메인 이름과 포트를 명시, 생략될 경우에는
웹 서비스 포트(80)로 이해
5.2 User-Agent
- 클라이언트를 식별할 수 있는 헤더
- User-Agent 헤더에 따라 서버의 동작이 달라지는 경우,
특정 앱들은 호환성을 위해 다른 User-Agent 정보를 사용하기도 함
//악성 봇들이나 자동화 프로그램도 가짜 User-agent 헤더를 사용하는 경우가 많음
->User-agent Spoofing
5.3 Accept, Accept-Language, Accept-Encoding
5.3.1 Accept 헤더는 클라이언트가 어떤 컨텐트 타입을 처리
할 수 있는지 서버에게 알려줌
5.3.2 Accept-Language 헤더는 클라이언트가
어떤 언어를 처리할 수 있는지 서버에게 알려줌
5.3.3 Accpet-Encoding 헤더는 클라이언트가
처리할 수 있는 인코딩 방식이나 압축 알고리즘 정보 알려줌
5.4 Referer
- 리피러 헤더는 이전 웹 페이지의 주소를 알려줌, 요청이 웹사이트
내부인지 외부인지 판단 가능 -> CSRF 대응
5.5 Content-Type, Content-Length
- 바디가 존재하는 경우 바디의 종류와 길이 알려줌
5.6 Cookie
5.6.1 쿠키를 전달하는 헤더, 변수와 값의 쌍으로 구성
5.6.2 여러 요청에 걸쳐 클라이언트에서
동일한 데이터를 전달할 필요가 있을 때 사용
Cookie: cookie1=value1, cookie2=value2
5.7 바디 //특정 사용자의 ID를 알아내어 해당 사용자만 권한을
가지고 있는 정보에 접근하는 것 -> 세션 하이재킹
- 데이터가 전송되는 부분
HTTP 응답 메시지
<버전><응답 코드><응답코드텍스트>
<헤더>
<바디>
1. 응답 코드/응답 코드 텍스트
- 헤더와 바디 부분 형식 동일
1.1 응답코드
1.1.1 100번대 : 정보 전달 목적
1.1.2 200번대 : 요청 처리 성공
1.1.3 300번대 : 다른 웹페이지로 리다이렉트 필요
1.1.4 400번대 : 클라이언트가 원인이 되어 에러 발생
1.1.5 500번대 : 서버 에러
2. 응답 헤더
2.1 Server
- 웹 서버와 웹 프레임워크의 버전 정보 알려줌
2.2 Set-cookie
- 서버에서 클라이언트로 쿠키를 전달할 때 사용, 쿠키 이름과 값 설정은 필수
Set-Cookie: <쿠키 이름>=<쿠키 값>; Expires=<날짜>; Path=<경로>; Secure; HttpOnly
2.2.1 Expires
- 쿠키의 유효기간 설정,
설정되어 있지 않으면 세션이 종료
될 때까지의 유효기간을 가짐
2.2.2 Path
- 쿠키를 전송할 리소스의 결로 짖어,
서브 디렉토리까지 같이 매칭
2.2.3 Secure
- 해당 옵션을 지정한 쿠키는 HTTPS 요청 시에만 전달
-> 네트워크 스니핑 대응
2.2.死 HttpOnly
- 해당 키워드를 통해 쿠키 값이 자바스크립트에
의해 접근되는 것을 방지 ->XSS 방지
2.2.5 X-Frame-Options
- <frame> or <iframe>를 사용한 웹 페이지 출력 제어 -> 클릭재킹 공격 방지
- ex: X-Frame-Options: Deny, X-Frame-Options: SAMEORIGIN
2.2.6 X-XSS-Protection
- XSS 공격이 탐지되었을 떄, 웹 페이지가 로딩되는 것을 막아줌
- ex: X-XSS-Protection: 1; mode=block
2.2.7 X-Content-Type-Options
- MIME 스니핑을 차단하기 위해 사용하는 헤더,
Content-Type에 설정된 형식으로만 처리
- ex: X-Content-Type-Options: nonsniff
0 notes
ryadel · 5 years ago
Text
Fetch API bug: can't GET or SET multiple Set-Cookie Headers
Tumblr media
Fetch is a new native JavaScript API that provides an interface for fetching resources (including across the network): according to Google Developers Documentation, "Fetch makes it easier to make web requests and handle responses than with the older XMLHttpRequest", thus applying to be the spiritual successor of the XHR-based approach (widely used by JQuery and the likes). As a matter of fact, Fetch API has been designed to be very familiar to anyone who has used XMLHttpRequest, while providing a more powerful and flexible feature set. The new API provides a generic definition of Request and Response objects, as well as other interface involved with network requests: such approach allow them to be used wherever they are needed in the future, whether it’s for service workers, Cache API, and other similar things that handle or modify requests and responses, or any kind of use case that might require you to generate your responses programmatically. It also defines related concepts such as Cross-Origin Resource Sharing (CORS) and the HTTP Origin header semantics, supplanting their separate definitions elsewhere. I've personally used Fetch API in most of my latest JavaScript projects, such as CORSflare - a pure JS Proxy specifically designed to overcome CORS-related and SameOrigin-based issues: however, today I've stumbled upon a major bug that, for the first time, led me to doubt that such interface is mature enough for production usage. Read the full article
0 notes
siberguvenlikwebtr · 5 years ago
Text
Clickjacking Saldırısı ve Korunma Yöntemleri
Tumblr media
Basitçe web sitelerinde kullanıcıların link gömülü görünmeyen bir sayfa elementine tıklamalarıyla farkında olmadan istemedikleri işlemlerin yaptırılmasına Clickjacking denir. Aşağıdaki örnekte kullanıcının gördüğü indirme sayfası ve bir indirme butonu ancak tüm sayfayı kaplayan bir iframe elementi saydam bir şekilde sayfaya eklenmiş. Saldırganın istediği kullanıcının sayfada herhangi bir yere tıklaması ve kullanıcı indir butonuna tıklayınca saldırganın istediği gerçekleşecek.
Tumblr media
Burada saldırgan görünmez linki tüm sayfayı kaplayacağı şekilde yapmış ancak sadece kullanıcı etkileşimi olan bölgeleri kullanarak da (buton, girdi elemanları vs) yapılabilir. Saldırı, kimlik bilgilerinin çalınması, kötü amaçlı yazılım yüklenmesi, saçma sapan sitelere yönlendirilmesi veya sosyal medya hesaplarının takip ettirilmesi gibi sonuçlar doğurabilir. Korunma Yöntemleri Kullanıcının bu saldırıdan en iyi korunma yöntemi bilmediği linklere tıklamamasıdır. Bir diğer alabileceği önlem de NoScript gibi eklentileri tarayıcıya yüklemektir. Bu eklentiler saydam şekilde bulunan linkleri engelleme özelliğine sahiptir. Site sahiplerinin ise kullanıcıları bu saldırıdan korunmaları için uygulayacakları en iyi yöntem HTTP Response Header’larına X-Frame-Options eklemektir. 3 türlü kullanılabilir: X-Frame-Options: DENY (içeriğin bir ,, veya ’ten yüklenmesini durdurur) X-Frame-Options: SAMEORIGIN (sadece mevcut sitedeki frame’lere izin verir) X-Frame-Options: ALLOW-FROM https://site.com/ (sadece URL’deki frame’lere izin verir.) Son olarak bu saldırıdan korunmada site sahiplerine daha çok iş düştüğünü de unutmayın.     Read the full article
0 notes
suzanneshannon · 5 years ago
Text
Easily adding Security Headers to your ASP.NET Core web app and getting an A grade
Well that sucks.
That's my podcast website with an F rating from SecurityHeaders.com. What's the deal? I took care of this months ago!
Turns out, recently I moved from Windows to Linux on Azure.
If I am using IIS on Windows, I can (and did) make a section in my web.config that looks something like this.
Do note that I've added a few custom things and you'll want to make sure you DON'T just copy paste this. Make yours, yours.
Note that I've whitelisted a bunch of domains to make sure my site works. Also note that I have a number of "unsafe-inlines" that are not idea.
<configuration> <system.webServer> <httpProtocol> <customHeaders> <add name="Strict-Transport-Security" value="max-age=31536000"/> <add name="X-Content-Type-Options" value="nosniff"/> <add name="X-Xss-Protection" value="1; mode=block"/> <add name="X-Frame-Options" value="SAMEORIGIN"/> <add name="Content-Security-Policy" value="default-src https:; img-src * 'self' data: https:; style-src 'self' 'unsafe-inline' www.google.com platform.twitter.com cdn.syndication.twimg.com fonts.googleapis.com; script-src 'self' 'unsafe-inline' 'unsafe-eval' www.google.com cse.google.com cdn.syndication.twimg.com platform.twitter.com platform.instagram.com www.instagram.com cdn1.developermedia.com cdn2.developermedia.com apis.google.com www.googletagservices.com adservice.google.com securepubads.g.doubleclick.net ajax.aspnetcdn.com ssl.google-analytics.com az416426.vo.msecnd.net/;"/> <add name="Referrer-Policy" value="no-referrer-when-downgrade"/> <add name="Feature-Policy" value="geolocation 'none';midi 'none';notifications 'none';push 'none';sync-xhr 'none';microphone 'none';camera 'none';magnetometer 'none';gyroscope 'none';speaker 'self';vibrate 'none';fullscreen 'self';payment 'none';"/> <remove name="X-Powered-By" /> <remove name="X-AspNet-Version" /> <remove name="Server" /> </customHeaders> </httpProtocol> ...
But, if I'm NOT using IIS - meaning I'm running my ASP.NET app in a container or on Linux - this will be ignored. Since I recently moved to Linux, I assumed (my bad for no tests here) that it would just work.
My site is hosted on Azure App Service for Linux, so I want these headers to be output the same way. There are several great choices in the form of Open Source NuGet libraries to help. If I use the ASP.NET Core middleware pipeline then these headers will be output and work the SAME on both Windows AND Linux.
I'll be using the NWebsec Security Libraries for ASP.NET Core. They offer a simple fluent way to add the headers I want.
TO BE CLEAR: Yes I, or you, can add these headers manually with AddHeader but these simple libraries ensure that our commas and semicolons are correct. They also offer a strongly typed middleware that is fast and easy to use.
Taking the same web.config above and translating it to Startup.cs's Configure Pipeline with NWebSec looks like this:
app.UseHsts(options => options.MaxAge(days: 30)); app.UseXContentTypeOptions(); app.UseXXssProtection(options => options.EnabledWithBlockMode()); app.UseXfo(options => options.SameOrigin()); app.UseReferrerPolicy(opts => opts.NoReferrerWhenDowngrade()); app.UseCsp(options => options .DefaultSources(s => s.Self() .CustomSources("data:") .CustomSources("https:")) .StyleSources(s => s.Self() .CustomSources("www.google.com","platform.twitter.com","cdn.syndication.twimg.com","fonts.googleapis.com") .UnsafeInline() ) .ScriptSources(s => s.Self() .CustomSources("www.google.com","cse.google.com","cdn.syndication.twimg.com","platform.twitter.com" ... ) .UnsafeInline() .UnsafeEval() ) );
There is one experimental HTTP header that NWebSec doesn't support (yet) called Feature-Policy. It's a way that your website can declare at the server-side "my site doesn't allow use of the webcam." That would prevent a bad guy from injecting local script that uses the webcam, or some other client-side feature.
I'll do it manually both to make the point that I can, but also that you aren't limited by your security library of choice.
NOTE: Another great security library is Andrew Lock's NetEscapades that includes Feature-Policy as well as some other great features.
Here's my single Middleware that just adds the Feature-Policy header to all responses.
//Feature-Policy app.Use(async (context, next) => { context.Response.Headers.Add("Feature-Policy", "geolocation 'none';midi 'none';notifications 'none';push 'none';sync-xhr 'none';microphone 'none';camera 'none';magnetometer 'none';gyroscope 'none';speaker 'self';vibrate 'none';fullscreen 'self';payment 'none';"); await next.Invoke(); });
Now I'll commit, build, and deploy (all automatic for me using Azure DevOps) and scan the site again:
That was pretty straightforward and took less than an hour. Your mileage may vary but that's the general idea!
Sponsor: Protect your apps from reverse engineering and tampering with PreEmptive, makers of Dotfuscator. Dotfuscator has been in-the-box with Microsoft Visual Studio since 2003. Mention HANSELMAN for savings on a professional license!
© 2020 Scott Hanselman. All rights reserved.
Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media
      Easily adding Security Headers to your ASP.NET Core web app and getting an A grade published first on https://deskbysnafu.tumblr.com/
0 notes
philipholt · 5 years ago
Text
Easily adding Security Headers to your ASP.NET Core web app and getting an A grade
Well that sucks.
That's my podcast website with an F rating from SecurityHeaders.com. What's the deal? I took care of this months ago!
Turns out, recently I moved from Windows to Linux on Azure.
If I am using IIS on Windows, I can (and did) make a section in my web.config that looks something like this.
Do note that I've added a few custom things and you'll want to make sure you DON'T just copy paste this. Make yours, yours.
Note that I've whitelisted a bunch of domains to make sure my site works. Also note that I have a number of "unsafe-inlines" that are not idea.
<configuration> <system.webServer> <httpProtocol> <customHeaders> <add name="Strict-Transport-Security" value="max-age=31536000"/> <add name="X-Content-Type-Options" value="nosniff"/> <add name="X-Xss-Protection" value="1; mode=block"/> <add name="X-Frame-Options" value="SAMEORIGIN"/> <add name="Content-Security-Policy" value="default-src https:; img-src * 'self' data: https:; style-src 'self' 'unsafe-inline' www.google.com platform.twitter.com cdn.syndication.twimg.com fonts.googleapis.com; script-src 'self' 'unsafe-inline' 'unsafe-eval' www.google.com cse.google.com cdn.syndication.twimg.com platform.twitter.com platform.instagram.com www.instagram.com cdn1.developermedia.com cdn2.developermedia.com apis.google.com www.googletagservices.com adservice.google.com securepubads.g.doubleclick.net ajax.aspnetcdn.com ssl.google-analytics.com az416426.vo.msecnd.net/;"/> <add name="Referrer-Policy" value="no-referrer-when-downgrade"/> <add name="Feature-Policy" value="geolocation 'none';midi 'none';notifications 'none';push 'none';sync-xhr 'none';microphone 'none';camera 'none';magnetometer 'none';gyroscope 'none';speaker 'self';vibrate 'none';fullscreen 'self';payment 'none';"/> <remove name="X-Powered-By" /> <remove name="X-AspNet-Version" /> <remove name="Server" /> </customHeaders> </httpProtocol> ...
But, if I'm NOT using IIS - meaning I'm running my ASP.NET app in a container or on Linux - this will be ignored. Since I recently moved to Linux, I assumed (my bad for no tests here) that it would just work.
My site is hosted on Azure App Service for Linux, so I want these headers to be output the same way. There are several great choices in the form of Open Source NuGet libraries to help. If I use the ASP.NET Core middleware pipeline then these headers will be output and work the SAME on both Windows AND Linux.
I'll be using the NWebsec Security Libraries for ASP.NET Core. They offer a simple fluent way to add the headers I want.
TO BE CLEAR: Yes I, or you, can add these headers manually with AddHeader but these simple libraries ensure that our commas and semicolons are correct. They also offer a strongly typed middleware that is fast and easy to use.
Taking the same web.config above and translating it to Startup.cs's Configure Pipeline with NWebSec looks like this:
app.UseHsts(options => options.MaxAge(days: 30)); app.UseXContentTypeOptions(); app.UseXXssProtection(options => options.EnabledWithBlockMode()); app.UseXfo(options => options.SameOrigin()); app.UseReferrerPolicy(opts => opts.NoReferrerWhenDowngrade()); app.UseCsp(options => options .DefaultSources(s => s.Self() .CustomSources("data:") .CustomSources("https:")) .StyleSources(s => s.Self() .CustomSources("www.google.com","platform.twitter.com","cdn.syndication.twimg.com","fonts.googleapis.com") .UnsafeInline() ) .ScriptSources(s => s.Self() .CustomSources("www.google.com","cse.google.com","cdn.syndication.twimg.com","platform.twitter.com" ... ) .UnsafeInline() .UnsafeEval() ) );
There is one experimental HTTP header that NWebSec doesn't support (yet) called Feature-Policy. It's a way that your website can declare at the server-side "my site doesn't allow use of the webcam." That would prevent a bad guy from injecting local script that uses the webcam, or some other client-side feature.
I'll do it manually both to make the point that I can, but also that you aren't limited by your security library of choice.
NOTE: Another great security library is Andrew Lock's NetEscapades that includes Feature-Policy as well as some other great features.
Here's my single Middleware that just adds the Feature-Policy header to all responses.
//Feature-Policy app.Use(async (context, next) => { context.Response.Headers.Add("Feature-Policy", "geolocation 'none';midi 'none';notifications 'none';push 'none';sync-xhr 'none';microphone 'none';camera 'none';magnetometer 'none';gyroscope 'none';speaker 'self';vibrate 'none';fullscreen 'self';payment 'none';"); await next.Invoke(); });
Now I'll commit, build, and deploy (all automatic for me using Azure DevOps) and scan the site again:
That was pretty straightforward and took less than an hour. Your mileage may vary but that's the general idea!
Sponsor: Protect your apps from reverse engineering and tampering with PreEmptive, makers of Dotfuscator. Dotfuscator has been in-the-box with Microsoft Visual Studio since 2003. Mention HANSELMAN for savings on a professional license!
© 2020 Scott Hanselman. All rights reserved.
Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media
      Easily adding Security Headers to your ASP.NET Core web app and getting an A grade published first on http://7elementswd.tumblr.com/
0 notes
tak4hir0 · 5 years ago
Link
実装した API の動作確認とテストをするときに,今までは curl と Postman を主に使っていたけど,最近は JetBrains エディタで使える「HTTP client」も併用している.今日は API リクエストをファイルに記述しコード化できる「HTTP client」の概要を紹介する.JetBrains のドキュメントは基本的に英語だけど pleiades.io なら日本語で読める. HTTP client in IntelliJ IDEA code editor - Help | IntelliJ IDEA IntelliJ IDEAコードエディターのHTTPクライアント - ヘルプ | IntelliJ IDEA 今回は検証環境として Sinatra を使った API を実装し,HTTP client から http://localhost:4567 にリクエストを送る.現在 RubyMine と GoLand のライセンスを購入しているため,今回は RubyMine を使って記事をまとめたけど,他の JetBrains エディタでも基本的に使える(IntelliJ IDEA だと Ultimate 限定). リクエストファイル まず「リクエストファイル」を作る.RunyMine で「New → HTTP Request」と選択することもできるし,新規ファイルの拡張子を .http もしくは .rest にして作ることもできる.最もシンプルなリクエストファイルは以下となる. GET http://localhost:4567/ping 今回はファイル名を api.http とした.ファイルを作成するとエディタは以下のような UI になる. 「Run All Requests in Files」ボタンもしくは GET の左にある「Run ▶」ボタンを押すとリクエストファイルを実行できる.実行すると「ヘッダー」と「レスポンス」を確認できる. GET http://localhost:4567/ping HTTP/1.1 200 OK Content-Type: text/html;charset=utf-8 Content-Length: 4 X-Xss-Protection: 1; mode=block X-Content-Type-Options: nosniff X-Frame-Options: SAMEORIGIN Server: WEBrick/1.4.2 (Ruby/2.5.1/2018-03-29) Date: Sat, 24 Dec 2019 14:00:00 GMT Connection: Keep-Alive pong Response code: 200 (OK); Time: 52ms; Content length: 4 bytes テンプレート機能 リクエストファイルで ⌘ + J と入力すると,以下の「計6種類」あるテンプレートから書き出せる.名前の略称は謎だけど,gt : GET と pt : POST と r : Request など,傾向はありそう. fptr : POST Request with file gtr : GET Request gtrp : GET Request with parameters mptr : POST Request with multipart ptr : POST Request ptrp : POST Request with parameters 例えば gtr を選択すると,以下のようにシンプルな GET リクエストを記述できる. GET http://localhost:80/api/item Accept: application/json ### 例えば ptr を選択すると,以下のようにシンプルな POST リクエストを記述できる. POST http://localhost:80/api/item Content-Type: application/json {} ### セパレータ機能 テンプレート機能を使うと自動的に末尾が ### になり,なんだろう?と気になると思う.これは「セパレータ」と言って,リクエストファイルの中に複数のリクエストを記述できることを意味している.以下は GET と POST の2種類のリクエストを記述している. GET http://localhost:4567/ping ### POST http://localhost:4567/users Content-Type: application/json { "name": "kakakakakku" } ### 「Run All Requests in Files」ボタンを押すとまとめて実行できるし,「Run ▶」ボタンを押すと個別に実行できる.以下のように結果もまとめて確認できる. Examples 機能 リクエストファイルのメニューバーにある「Examples」ボタンを押すと HTTP client に同梱されたリクエストファイルの具体的な記述例を確認できる.現在は「計4種類」あり,実行することもできる. Get Requests Post Requests Requests with Authorization Requests with Tests 個人的には「���ンプレート機能」よりも使う場面が多いと思う.変数を使ったり,認証をしたり,応答ハンドラスクリプトを書いたり(後述),すぐに使える記述例をコピーできる. Convert from cURL 機能 リクエストファイルのメニューバーにある「Convert from cURL」ボタンを押すと,curl コマンドをリクエストファイルの記述に変換できる.既存スクリプトを HTTP client に移行しやすくなる便利な機能だと思う. 変数機能 HTTP client には「動的変数」と「環境変数」がある.「動的変数」は計3種類あり,自動的に値を設定してくれる.要件に合う場合に使える. $uuid : UUID を返す $timestamp : UNIX Timestamp を返す $randomInt : 0 - 1000 の範囲から乱数を返す 実際にリクエストファイルを記述すると以下のようになる. POST http://localhost:4567/logging Content-Type: application/json { "uuid": "", "randomInt": "", "timestamp": "" } ### 「環境変数」は環境ごとに任意の値を設定できる.まず,環境設定を記述する http-client.env.json もしくは rest-client.env.json を作成する.今回は dev 環境と prd 環境に name 変数を定義するファイルを作成する. { "dev": { "name": "kakakakakku-dev" }, "prd": { "name": "kakakakakku-prd" } } リクエストファイルには と記述する. POST http://localhost:4567/users Content-Type: application/json { "name": "" } ### すると「Run All Requests in Files」ボタンを押して実行するときに環境を選択できるようになり,該当する環境変数が設定される. 応答ハンドラスクリプト機能 「応答ハンドラスクリプト機能」を使うと,リクエストファイルを実行した後にレスポンスを検証し,テストコードを記述できるようになる.ハンドラスクリプト自体は JavaScript を使う.例えば,以下はレスポンスコード 200 と 404 に対して response.status === 200 という条件で検証している. GET https://httpbin.org/status/200 {% client.test("Request executed successfully", function() { client.assert(response.status === 200, "Response status is not 200"); }); %} ### GET https://httpbin.org/status/404 {% client.test("Request executed successfully", function() { client.assert(response.status === 200, "Response status is not 200"); }); %} 実行すると,期待した通りに2個目のテストは落ちる.もしかしたら簡単な TDD もできそう! ログ機能 作業ディレクトリの .idea/httpRequests/ 直下に HTTP client のログが「最大50件」保存されている.さらにリクエストファイルのメニューバーにある「Open Log」ボタンを押すと,ログを確認しながら「Run ▶」ボタンで個別に再実行もできる. 機能は他にもある 今回紹介しなかった機能もある.例えば以下など. リクエストファイルにコメントを書く 認証のために Authorization ヘッダーを送信する(Basic 認証 / Digest認証) リダイレクトに対応する リクエストファイルの具体的な解説は以下のドキュメントにある. Exploring the HTTP request in Editor syntax - Help | IntelliJ IDEA エディター構文でのHTTPリクエストの調査 - ヘルプ | IntelliJ IDEA リクエストファイルの構文仕様は GitHub に載っている. github.com まとめ JetBrains エディタで使える「HTTP client」は API リクエストをファイルに記述できる.今回紹介した多くの機能を使ってリッチな API の動作確認とテストを実現できるし,何よりもチーム開発においては「リクエストファイルをコード化してリポジトリで管理できる」という点に価値がある.最近は個人 GitHub リポジトリに api.http を置くようにしている. とは言え,メンバー全員を JetBrains エディタに統一するのは本質的ではなく,例えば VS Code など他のエディタでもリクエストファイルを認識できると良さそう.調べてみると,リクエストファイルをサポートする拡張機能「REST Client」はあるけど,構文が微妙に違う気がする. REST Client - Visual Studio Marketplace 「HTTP client」 を使って API リクエストをコード化しよう!
0 notes
sololinuxes · 6 years ago
Text
Generador online de .htaccess
Tumblr media
Generador online de .htaccess (htaccess online generator). Revisando los repositorios de Github, encontré un generador online de .htaccess que quiero compartir con los lectores de "Sololinux". Al ver el código, me sorprendió el buen diseño y trabajo que el amigo Emirodgar había realizado. El resultado final está muy elaborado, y cuenta con excelentes características, que pasamos a enumerar: Opciones de acceso Establece el dominio principal. Redireccionamiento a www. https redirect. Opciones de configuración Página de acceso predeterminada. Juego de caracteres predeterminado. Forzar la descarga de un tipo de archivo. Limitar el tamaño del archivo a subir. Configurar el correo del administrador. Actuación Activar la compresión Gzip. Habilitar los encabezados de Keep-Alive. Vencimiento de los encabezados (headers). Páginas de error personalizadas Error 404 Error 500 Opciones de seguridad Bloquear la navegación por el directorio. Deshabilitar la ejecución de CGI. Oculta la información sensible del servidor. Evitar que inserten tus páginas en otros sitios web. Deshabilita la firma del servidor. Bloquea los robots de SPAM más conocidos. Evita el acceso ilegal o inseguro. No permitir la ejecución de scripts (define las extensiones). Deniega los métodos de solicitud que definas. No permite el hotlinking. Antes de realizar cualquier modificación en tu archivo htaccess, te recomiendo que hagas una copia de seguridad. Es algo típico que por cualquier error en el archivo, el servidor lance un error 500.
Tumblr media
  Generador online de .htaccess
Como considero que es una utilidad altamente recomendable, la hemos subido a sololinux, para que puedas generar tu archivo htaccess, lo encontraras en la siguiente url. htaccess online generator Si prefieres tener tu propio generador online de .htaccess, es tan simple como crear un archivo html y copiar y pegar lo siguiente. Free .htaccess Online Generator body { padding-top: 2rem; padding-bottom: 2rem; } h3 { margin-top: 2rem; } h2 { font-size: 1.45rem; margin-top: 2rem; margin-bottom: 2rem; } form { padding-left:10px; } .row { margin-bottom: 1rem; } .row .row { margin-top: 1rem; margin-bottom: 0; } { padding-top: 1rem; padding-bottom: 1rem; background-color: rgba(86,61,124,.15); border: 1px solid rgba(86,61,124,.2); } hr { margin-top: 2rem; margin-bottom: 2rem; } .lead, small { padding-left:10px; } footer {padding: 2rem;} (function(w,d,s,l,i){w=w||;w.push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s), j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-K8V5396');
Free .htaccess Generator
Simple, free and online. Create, without error, your .htaccess file. Instructions Fill the options and push "generate" button in order to get your .htaccess file. The copy and paste the content into your .htaccess file. Remember, this file must be in the root of your site.
Public access options
Domain Example: domain.com (don't use www or http) Redirect http to https (SSL) Force www access (default is non www)
Config website
Prevent 404 errors for non-existing folders Default access page Example: index.php index.html (default is index.html) Default web charset Example: UTF-8 Force download (filetype) Example: .avi .pdf .mp4 Limit upload file size Example: 2147483647 (2GB) Administrator email Example: [email protected]
Performance
Enable Gzip compression Enable Keep-Alive header Expires Headers Example: 29030400 Time helper 30 min 1 hour 12 hours 1 day 1 week 1 month 1 year
Custom errors pages
Error 404 Example: error404.html Error 500 Example: error500.html
Security
Prevent directory navigation Disable CGI execution Hide information about web server technology Do not allow pages to be framed Disable server sign Block SPAM bots Prevent illegal or unsafe access (restrictive mode) Disallow script execution Example: .php .jsp .cgi Deny requests methods Example: get|post|put Prevent hotlinking Example: https://mydomain.com/mylogo.png Generate .htaccess Created by Emirodgar - Free htaccess generator $('#generateHtaccess').click( function() { var htaccess = ''; var domain = $('#htDomain').val(); var domainReg = domain.replace(/\./g,'\\.'); if (domainReg =='') domainReg = 'CHANGEDOMAIN\\.com'; var param = paramHttps = htaccessIllegal = htaccessSpam = ''; var rewrite = false; $('#htaccessFinal').val(''); htaccess += '\nRewriteEngine On'; if ($('#htHttps').is(":checked")) { paramHttps = 's'; htaccess += "\n\n#Redirect to SSL version"+ "\nRewriteCond %{HTTPS} off" + "\nRewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI}"; } if ($('#htWww').is(":checked")) { htaccess += "\n\n#Redirect to www version"+ "\nRewriteCond %{HTTP_HOST} !^www\.(.*)$ " + "\nRewriteRule ^(.*)$ http"+paramHttps+"://www.%{HTTP_HOST}/$1"; } else { $param = 'www.'; htaccess += "\n\n#Redirect to non www version"+ "\nRewriteCond %{HTTP_HOST} ^www\.(.*)$ " + "\nRewriteRule ^(.*)$ http"+paramHttps+"://%1/$1 "; } //Config if ($('#ht404Redirect').is(":checked")) { htaccess += "\n\n#Prevent 404 en non-existing folders"+ "\nOptions -MultiViews"; } var htDefaultPage = $('#htDefaultPage').val(); if(htDefaultPage!=''){ htaccess += "\n\n#Default page"+ "\nDirectoryIndex "+htDefaultPage; } var htAdminEmail = $('#htAdminEmail').val(); if(htAdminEmail!=''){ htaccess += "\n\n#Default contact email"+ "\nSetEnv SERVER_ADMIN "+htAdminEmail; } var htForceDownload = $('#htForceDownload').val(); if(htForceDownload!=''){ htaccess += "\n\n#Force download"+ "\nAddType application/octet-stream "+htForceDownload; } var htWebCharset = $('#htWebCharset').val(); if(htWebCharset!=''){ htaccess += "\n\n#Default charset"+ "\nAddDefaultCharset "+htWebCharset; } var htFileSize = $('#htFileSize').val(); if(htFileSize!=''){ htaccess += "\n\n#Limit upload file size"+ "\nLimitRequestBody "+htFileSize; } //Performance if ($('#htGzip').is(":checked")) { htaccess += "\n\n#Gzip compression"+ "\n"+ "\n mod_gzip_on Yes"+ "\n mod_gzip_dechunk Yes"+ "\n mod_gzip_item_include file .(html?|txt|css|js|php|pl)$"+ "\n mod_gzip_item_include handler ^cgi-script$"+ "\n mod_gzip_item_include mime ^text/.*"+ "\n mod_gzip_item_include mime ^application/x-javascript.*"+ "\n mod_gzip_item_exclude mime ^image/.*"+ "\n mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*"+ "\n"; } if ($('#htKeepAlive').is(":checked")) { htaccess += "\n\n#Enable Keep-Alive Headers"+ "\n"+ "\n Header set Connection Keep-Alive"+ "\n"; } var htExpiresHeaders = $('#htExpiresHeaders').val(); var htExpiresHeadersFormat = $('#htExpiresHeadersFormat').val(); if(htExpiresHeaders!=''){ htaccess += "\n\n#Set Expires Headers"+ '\n'+ "\n ExpiresDefault A"+htExpiresHeaders+ "\n"; } //Error var htCustomError404 = $('#htCustomError404').val(); if(htCustomError404!=''){ htaccess += "\n\n#Default 404 error"+ "\ErrorDocument 404 "+htCustomError404; } var htCustomError500 = $('#htCustomError500').val(); if(htCustomError500!=''){ htaccess += "\n\n#Default 500 error"+ "\nErrorDocument 500 "+htCustomError404; } //Security if ($('#htDirectory').is(":checked")) { htaccess += "\n\n#Prevent directory navigation"+ "\nOptions All -Indexes"; } if ($('#htDisableCgi').is(":checked")) { htaccess += "\n\n#Disable CGI"+ "\nOptions -ExecCGI"; } if ($('#htDisableTech').is(":checked")) { htaccess += "\n\n#Hide PoweredBy"+ "\nHeader unset X-Powered-By"; } if ($('#htDisableFrame').is(":checked")) { htaccess += "\n\n#Do not allow pages to be framed"+ "\nHeader set X-Frame-Options SAMEORIGIN"; } if ($('#htDisableSign').is(":checked")) { htaccess += "\n\n#Disable server sign"+ "\nServerSignature Off"; } var htDisallowScript = $('#htDisallowScript').val(); if(htDisallowScript!=''){ htaccess += "\n\n#Disallow scripts execution"+ "\nAddHandler " +htDisallowScript; } var htDenyRequests = $('#htDenyRequests').val(); if(htDenyRequests!=''){ htaccess += "\n\n#Deny request method"+ "\nRewriteCond %{REQUEST_METHOD} !^("+htDenyRequests.toUpperCase()+")"+ "\nRewriteRule .? - "; } var htHotlinking = $('#htHotlinking').val(); if(htHotlinking!=''){ htaccess += "\n\n#Prevent hotlinking"+ "\nRewriteCond %{HTTP_REFERER} !^$"+ "\nRewriteCond %{HTTP_REFERER} !^http://(www\.)?"+domainReg+"/.*$ "+ "\nRewriteRule \.(gif|jpg|swf|flv|png)$ "+htHotlinking+" "; } if ($('#htSpamBots').is(":checked")) { rewrite= true; htaccessSpam = "\n\n #Block Spam Bots"+ "\n RewriteCond %{HTTP_USER_AGENT} ^(aesop_com_spiderman|alexibot|backweb|bandit|batchftp|bigfoot) " + "\n RewriteCond %{HTTP_USER_AGENT} ^(black.?hole|blackwidow|blowfish|botalot|buddy|builtbottough|bullseye) " + "\n RewriteCond %{HTTP_USER_AGENT} ^(cheesebot|cherrypicker|chinaclaw|collector|copier|copyrightcheck) " + "\n RewriteCond %{HTTP_USER_AGENT} ^(cosmos|crescent|curl|custo|da|diibot|disco|dittospyder|dragonfly) " + "\n RewriteCond %{HTTP_USER_AGENT} ^(drip|easydl|ebingbong|ecatch|eirgrabber|emailcollector|emailsiphon) " + "\n RewriteCond %{HTTP_USER_AGENT} ^(emailwolf|erocrawler|exabot|eyenetie|filehound|flashget|flunky) " + "\n RewriteCond %{HTTP_USER_AGENT} ^(frontpage|getright|getweb|go.?zilla|go-ahead-got-it|gotit|grabnet) " + "\n RewriteCond %{HTTP_USER_AGENT} ^(grafula|harvest|hloader|hmview|httplib|httrack|humanlinks|ilsebot) " + "\n RewriteCond %{HTTP_USER_AGENT} ^(infonavirobot|infotekies|intelliseek|interget|iria|jennybot|jetcar) " + "\n RewriteCond %{HTTP_USER_AGENT} ^(joc|justview|jyxobot|kenjin|keyword|larbin|leechftp|lexibot|lftp|libweb) " + "\n RewriteCond %{HTTP_USER_AGENT} ^web(zip|emaile|enhancer|fetch|go.?is|auto|bandit|clip|copier|master|reaper|sauger|site.?quester|whack) " + "\n RewriteCond %{HTTP_USER_AGENT} ^.*(craftbot|download|extract|stripper|sucker|ninja|clshttp|webspider|leacher|collector|grabber|webpictures).*$ " + "\n RewriteRule . - "; } if ($('#htIllegal').is(":checked")) { rewrite= true; htaccessIllegal = "\n\n #Block illegal or unsafe access"+ "\n RewriteCond %{REQUEST_METHOD} ^(HEAD|TRACE|DELETE|TRACK) " + "\n RewriteCond %{THE_REQUEST} ^.*(\\r|\\n|%0A|%0D).* " + "\n RewriteCond %{HTTP_COOKIE} ^.*(|'|'|%0A|%0D|%27|%3C|%3E|%00).* " + "\n RewriteCond %{HTTP_USER_AGENT} ^.*(|'|'|%0A|%0D|%27|%3C|%3E|%00).* " + "\n RewriteCond %{QUERY_STRING} ^.*(localhost|loopback|127\.0\.0\.1).* " + "\n RewriteCond %{QUERY_STRING} ^.*(|'|'|%0A|%0D|%27|%3C|%3E|%00).* " + "\n RewriteRule (.*) - "; } if (rewrite == true){ htaccess += "\n\n#Mod Rewrite"+ "\n"+ "\n RewriteEngine On"+ "\n Options +FollowSymlinks"+ "\n RewriteBase /"+ htaccessSpam+ htaccessIllegal+ "\n"; } $('#htaccessFinal').val(htaccess); } ); Guardas el *.html y lo ejecutas en tu navegador web favorito. Ejemplo...
Tumblr media
  Si crees que esta herramienta es útil, compártela.   Read the full article
0 notes
quangvublog · 5 years ago
Text
Hướng dẫn cấu hình Nginx sử dụng Let’s Encrypt trên Ubuntu 18.04
Lets’s Encrypt là một certificate authority (cơ quan cấp chứng chỉ) mở và miễn phí được phát triển bởi Internet Security Research Group (ISRG). Chứng chỉ được ban hành bởi Let’s Encrypt được hầu hết các trình duyệt web hiện đại ngày nay tin tưởng.
Trong bài viết này, mình sẽ hướng dẫn các bạn cách thiết lập bảo mật HTTPS cho website sử dụng Let’s Encrypt trên Nginx sử dụng công cụ certbot trên Ubuntu 18.04.
Yêu cầu
Trước khi bắt đầu, bạn cần phải đảm bảo chuẩn bị và đáp ứng những yêu cầu sau đây trước khi tiến hành thực hiện theo bài hướng dẫn này.
DNS tên miền đã trỏ tới đúng IP public của server mà bạn sẽ thực hiện cài đặt. Trong bài viết này, mình sẽ sử dụng domain vu-review.com.
Server đã cài đặt sẵn Nginx
Hướng dẫn cài đặt Certbot
Certbot là một công cụ đầy đủ các tính năng và dễ dàng sử dụng, cho phép chúng ta tự động hóa các tác vụ để lấy và làm mới chứng chỉ SSL của Let’s Encrypt và cấu hình web server sử dụng chứng chỉ. Gói certbot có sẵn trong repository của Ubuntu rồi, nên bạn chỉ cần dùng câu lệnh apt để cài đặt thôi.
Cập nhật danh sách các packages và cài đặt gói certbot như sau:
sudo apt update sudo apt install certbot
Tạo nhóm DH (Diffie-Hellma)
Trao đổi khóa Diffie–Hellman (DH) là một cơ chế trao đổi khóa mã hóa (cryptographic keys) qua một kênh giao tiếp không an toàn. Mình sẽ tạo ra một tập tham số 2048 bit DH mới để tăng cường bảo mật.
sudo openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048
Nếu thích, bạn cũng có thể thay đổi kích cỡ lên tới 4096 bits, nhưng trong trường hợp này, quá trình khởi tạo key có thể lên tới 10 phút – tùy thuộc vào entropy hệ thống.
Nhận chứng chỉ SSL của Let’s Encrypt
Để nhận chứng chỉ SSL cho domain của mình, mình sẽ sử dụng plugin Webroot – nó sẽ tạo ra một file tạm để xác thực domain được truy vấn trong thư mục ${webroot-path}/.well-known/acme-challenge
Để đơn giản hơn, mình sẽ map tất cả các request HTTP có đường dẫn .well-known/acme-challenge tới thư mục là /var/lib/letsencrypt.
Các câu lệnh sau đây sẽ tạo ra thư mục cho phép nó có thể ghi tới server Nginx.
sudo mkdir -p /var/lib/letsencrypt/.well-known sudo chgrp www-data /var/lib/letsencrypt sudo chmod g+s /var/lib/letsencrypt
Để tránh trùng lặp mã, mình sẽ tạo ra 2 đoạn mã trong block của server Nginx.
Đầu tiên, mở vim lên tạo đoạn mã đầu tiên là letsencrypt.conf:
sudo vi /etc/nginx/snippets/letsencrypt.conf
Sau đó dán đoạn mã này vào
location ^~ /.well-known/acme-challenge/ { allow all; root /var/lib/letsencrypt/; default_type "text/plain"; try_files $uri =404; }
Tạo đoạn mã thứ hai là ssl.conf đây là đoạn mã chứa các đề xuất như OCSP Stapling, HTTP Strict Transport Security (HSTS) và security‑focused HTTP headers của FireFox.
sudo nano /etc/nginx/snippets/ssl.conf
Dán đoạn mã này vào
ssl_dhparam /etc/ssl/certs/dhparam.pem; ssl_session_timeout 1d; ssl_session_cache shared:SSL:50m; ssl_session_tickets off; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers 'ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS'; ssl_prefer_server_ciphers on; ssl_stapling on; ssl_stapling_verify on; resolver 8.8.8.8 8.8.4.4 valid=300s; resolver_timeout 30s; add_header Strict-Transport-Security "max-age=15768000; includeSubdomains; preload"; add_header X-Frame-Options SAMEORIGIN; add_header X-Content-Type-Options nosniff;
Sau khi đã khởi tạo và lưu 2 đoạn mã trên, mở block domain có chứaletsencrypt.confvào như sau:
sudo vi /etc/nginx/sites-available/vu-review.com.conf
Sau đó dán đoạn mã này vào
server { listen 80; server_name vu-review.com www.vu-review.com; include snippets/letsencrypt.conf; }
Để kích hoạt file block server mới, mình cần phải tạo một symbolic link từ file này với thư mục sites-enabled – đây là thư mục được Nginx đọc trong quá trình startup.
sudo ln -s /etc/nginx/sites-available/vu-review.com.conf /etc/nginx/sites-enabled/
Sau đó, khởi đọng lại nginx
sudo systemctl restart nginx
Bây giờ, bạn có thể chạy Certbot với plugin webhoot và nhận file chứng chỉ SSL bằng cách chạy lệnh sau:
sudo certbot certonly --agree-tos --email [email protected] --webroot -w /var/lib/letsencrypt/ -d vu-review.com -d www.vu-review.com
Nếu như nhận được chứng chỉ SSL thành công, certbot sẽ in ra message có dạng như sau:
IMPORTANT NOTES: - Congratulations! Your certificate and chain have been saved at: /etc/letsencrypt/live/vu-review.com/fullchain.pem Your key file has been saved at: /etc/letsencrypt/live/vu-review.com/privkey.pem Your cert will expire on 2020-06-13. To obtain a new or tweaked version of this certificate in the future, simply run certbot again. To non-interactively renew *all* of your certificates, run "certbot renew" - Your account credentials have been saved in your Certbot configuration directory at /etc/letsencrypt. You should make a secure backup of this folder now. This configuration directory will also contain certificates and private keys obtained by Certbot so making regular backups of this folder is ideal. - If you like Certbot, please consider supporting our work by: Donating to ISRG / Let's Encrypt: https://letsencrypt.org/donate Donating to EFF: https://eff.org/donate-le
Bây giờ mình đã có được file chứng chỉ rồi, mình có thể edit block server domain lại để sử dụng SSL thành dạng như sau:
sudo vi /etc/nginx/sites-available/vu-review.com.conf
# Redirect HTTP -> HTTPS server { listen 80; server_name www.vu-review.com vu-review.com; include snippets/letsencrypt.conf; return 301 https://vu-review.com$request_uri; } # Redirect WWW -> NON WWW server { listen 443 ssl http2; server_name www.vu-review.com; ssl_certificate /etc/letsencrypt/live/vu-review.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/vu-review.com/privkey.pem; ssl_trusted_certificate /etc/letsencrypt/live/vu-review.com/chain.pem; include snippets/ssl.conf; return 301 https://vu-review.com$request_uri; } server { listen 443 ssl http2; server_name vu-review.com; root /var/www/html/vu-review.com; index index.php; # SSL parameters ssl_certificate /etc/letsencrypt/live/vu-review.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/vu-review.com/privkey.pem; ssl_trusted_certificate /etc/letsencrypt/live/vu-review.com/chain.pem; include snippets/ssl.conf; include snippets/letsencrypt.conf; # log files access_log /var/log/nginx/vu-review.com.access.log; error_log /var/log/nginx/vu-review.com.error.log; location = /favicon.ico { log_not_found off; access_log off; } location = /robots.txt { allow all; log_not_found off; access_log off; } location / { try_files $uri $uri/ /index.php?$args; } location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/run/php/php7.2-fpm.sock; } location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ { expires max; log_not_found off; } }
Với cấu hình bên trên mình đã ép website phải sử dụng HTTPS và chuyển hướng từ www sang non-www.
Reload lại Nginx server để các thay đổi ảnh được thực hiện ngay lập tức.
sudo systemctl reload nginx
Làm mới tự động chứng chỉ SSL của Let’s Encrypt
Chứng chỉ SSL của Let’s Encrypt chỉ có hiệu lực vỏn vẹn trong vòng 90 ngày thôi. Để tự động làm mới chứng chỉ trước khi nó hết hạn, certbot tạo ra một cronjob chạy 2 lần mỗi ngày và sẽ tự động làm mới chứng chỉ bất kỳ chứng chỉ nào sau 30 ngày nữa sẽ hết hạn.
Vì mình sẽ sử dụng plugin webroot certbot khi mà chứng chỉ SSL đã được làm mới, mình cũng sẽ cần phải reload lại nginx. Lúc này, mình sẽ thêm --renew-hook "systemctl reload nginx" vào file  /etc/cron.d/certbot
sudo vi /etc/cron.d/certbot
0 */12 * * * root test -x /usr/bin/certbot -a \! -d /run/systemd/system && perl -e 'sleep int(rand(3600))' && certbot -q renew --renew-hook "systemctl reload nginx"
Để kiểm tra quá trình làm mới, bạn có thể sử dụng certbot với option --dry-run
sudo certbot renew --dry-run
Nếu không có lỗi nào cả, nghĩa là quá trình làm mới chứng chỉ thành công rồi đấy.
Kết luận
Trong bài viết này, mình đã sử dụng Let’s Encrypt để download chứng chỉ SSL cho domain vu-review.com của mình. Và tạo 2 đoạn code Nginx để tránh trùng lặp code và cấu hình Nginx khi sử dụng chứng chỉ. Và sau cùng, dùng cronjob để tự động làm mới chứng chỉ SSL trước khi nó hết hạn.
The post Hướng dẫn cấu hình Nginx sử dụng Let’s Encrypt trên Ubuntu 18.04 appeared first on Quang Vũ Blog.
source https://blog.vu-review.com/lets-encrypt-nginx.html
0 notes
awsexchage · 7 years ago
Photo
Tumblr media
Qiitaのコメント数表示がおかしくなったので調べてみた https://ift.tt/2QgJaiC
追記(解消されたとのことです)
Qiita:Supportに問い合わせしていたのですが、コメント数がおかしかった件について、すでに調査・対応が完了し問題が解消したと返答いただきました。(2018/11/12 12時)
今回の問題は深刻なケース(○○機能が使えない)には該当しない判断らしく、アナウンスはないとのことでした。個人的には深刻でしたけれど
概要
先日、自動投稿しているQiitaのコメントランキング記事にコメントついてない記事なのにランキングされているとコメントを���ただきました。(2018/11/ 09 20時くらい
https://qiita.com/kai_kou/items/df87ebf338389a39062c#comment-27fc341d01e60398165a
Tumblr media
なんだろうなぁと思って調べてみました。
調査
ランキングはQiita API v2を利用して記事を取得して集計しているので、APIを確認してみました。とりあえず自分の記事をみてみます。
> curl "https://qiita.com/api/v2/items?query=user:kai_kou" \ | jq -r '.[] | [.comments_count, .title, .id] | @csv' 0,"PythonのFlaskでAPI開発するときの参考記事まとめ","889b016e19203fac5c9d" 1,"Flask-RESTfulとFlask-SQLAlchemyを利用してリソースをネストしてJSONを返す方法","9dea3a08c1577a6dd952" 2,"PythonでQiitaに予約投稿できるツールをさくっと作ってみた(使い方編)","9129f0cc5249a039d11d" 1,"Google Cloud Functionsでgoogle-api-python-clientを利用してfile_cache is unavailableエラーになったときの対応方法","4b754c61ac225daa0f7d" 0,"MacOSのSafariでCORS制限を無効化する設定があって開発時に便利でした","54b61a274b77977add54" 0,"Pythonの標準ライブラリでさくっとAPIサーバとWebサーバを立ち上げる","6cf5930330b85fa583b0" 0,"Google App Engine上でFlaskを利用してNo Content(204)を返すとき、 ```Content-Length``` が0じゃないとエラーになる","a4204189b1b9d4b74dc9" 0,"Google App Engine上のFlaskでレスポンスをNo Content(204)で返す方法を調べた","801ae9715b5b8f4736b8" 0,"PythonでCLIツールを作成するのにdocoptでパラメータのパーサー作成を自動化する","5ff0958264c56ecf0a17" 0,"SQLAlchemyをMySQLで主キーをUUIDにするならSQLAlchemy-Utilsが便利","70d73af54c2550051607" 1,"Qiitaの限定共有投稿で意図せずユーザーメンションすると通知がされて迷惑になるので注意しましょう","1bdd5d80a9e2180eca45" 0,"Qiita API v2を利用してcurlで投稿してみた","663d3f7bbc4da4ccf62d" 0,"MacでCloud SQL Proxy Dockerイメージを利用して接続するとき```x509: certificate signed by unknown authority``` エラーが出たときの対応","167d670c1d7a108dde4b" 3,"docker-compose.ymlでDockerfileを指定したい","eaafa3cb15e1496f50ec" 0,"GCPのgcloudコマンドからGoogle Issue TrackerにIssueを登録してみる","9db1d3405ee73280737c"
そんなにコメントをいただける記事が書けてないはずなのに、いくつかコメント数がついてます。最近投稿した記事をさらにみてみます。
確認する記事
2,"PythonでQiitaに予約投稿できるツールをさくっと作ってみた(使い方編)","9129f0cc5249a039d11d"
> curl "https://qiita.com/api/v2/items/9129f0cc5249a039d11d" \ | jq -r '.[] | [.comments_count, .title, .id] | @csv' 2,"PythonでQiitaに予約投稿できるツールをさくっと作ってみた(使い方編)","9129f0cc5249a039d11d"
記事をピンポイントで取得してもcomments_count の数は変わらず。コメントを取得してみます。
> curl -i "https://qiita.com/api/v2/items/9129f0cc5249a039d11d/comments" | jq HTTP/2 200 date: Sat, 10 Nov 2018 01:46:50 GMT content-type: application/json; charset=utf-8 server: nginx x-frame-options: SAMEORIGIN x-xss-protection: 1; mode=block x-content-type-options: nosniff link: ; rel="first", ; rel="next", ; rel="last" total-count: 0 etag: W/"4f53cda18c2baa0c0354bb5f9a3ecbe5" cache-control: max-age=0, private, must-revalidate rate-limit: 60 rate-remaining: 50 rate-reset: 1541817594 vary: Origin x-runtime: 0.105595 strict-transport-security: max-age=2592000 x-request-id: 39dd51d5-e59f-4bd8-b70d-5ae64a77c564 []
はい。 空っぽです。total-count も0 です。悲しい
APIだけかなと思ったのですが、Qiitaサイトで確認しても同じ状況でした。悲しい
Tumblr media Tumblr media
想像
投稿情報items に含まれるcomments_count の数値が実コメント数となっていないので、最近、そのへんを改修して、デグレでも起こした感じでしょうか?あらまあ
コメントランキングを作成しているツールについては上記のようにcomments から正しいコメント数を取得して対応中で、その際に各記事のコメントを確認できるようにしたのですが、限定共有投稿も同じ状態だったり、設定される数字もバラバラで法則性が見えませんでした。
Tumblr media
まとめ
@Qiitaの中の人!修正はよ!はよ!
参考
jq コマンドを使う日常のご紹介 https://qiita.com/takeshinoda@github/items/2dec7a72930ec1f658af
元記事はこちら
「Qiitaのコメント数表示がおかしくなったので調べてみた」
November 26, 2018 at 04:00PM
0 notes
securitynewswire · 7 years ago
Text
Response header name interning does not have sameorigin protections and th
SNNX.com : Response header name interning does not have sameorigin protections and th http://dlvr.it/QdJcvz
0 notes
dougsparlingdotorg · 7 years ago
Text
Using cURL to Test the WordPress Theme and Plugin APIs
Occasionally (rarely) when trying to search for a theme or plugin via the WordPress dashboard, you may see an error like this:
An unexpected error occurred. Something may be wrong with WordPress.org or this server’s configuration. If you continue to have problems, please try the support forums.
This means that the request WordPress has made to the theme or plugins api has failed, or that the body of the response is bad or empty. Often web hosts will turn off outbound http requests and this will be the source of your problem. However, there can be a myriad of other issues that may cause this error. WordPress will use one of three “transports” and search for them on your server in this order: curl, streams, and fsockopen. Since the focus of this article is on using cURL, that’s what will use at the command line.
To check if cURL is installed on your server, use the Unix ‘which’ command to find it’s install location.
$ which curl
and you should get a response something like this (your path may vary):
/usr/bin/curl
To simply check connectivity with the WordPress theme and plugin apis, you can make an http HEAD request with cURL:
$ curl -I http://api.wordpress.org/plugins/info/1.0/
and
$ curl -I http://api.wordpress.org/themes/info/1.0/
You should see output something like this:
HTTP/1.1 200 OK Server: nginx Date: Mon, 09 Jul 2018 16:41:02 GMT Content-Type: text/html; charset=utf-8 Connection: keep-alive Vary: Accept-Encoding X-Frame-Options: SAMEORIGIN
If you don’t have connectivity, you may see something like this:
>curl: (6) Could not resolve host: api.wordpress.org; nodename nor servname provided, or not known
If you want to duplicate the request made when you’re actually on the WordPress dashboard, you’ll have to make a POST request with serialized data parameters. To mimic a search for a “blue” theme, use this cURL command:
$ curl --data 'action=query_themes&request=O:8:"stdClass":4:{s:4:"page";i:1;s:8:"per_page";i:36;s:6:"fields";N;s:6:"search";s:4:"blue";}' http://api.wordpress.org/themes/info/1.0/
To mimic a search for a “cache” plugin, use this command:
$ curl --data 'action=query_plugins&request=O:8:"stdClass":3:{s:4:"page";i:1;s:8:"per_page";i:30;s:6:"search";s:5:"cache";}' http://api.wordpress.org/plugins/info/1.0/
A successful request will return quite a bit of HTML and serialized data (which I won’t post here).
0 notes
ryadel · 5 years ago
Text
CORSflare - Free Reverse Proxy to bypass same-origin restrictions
Tumblr media
CORSflare is a reverse proxy written in JavaScript that can be used to bypass most common Cross-Origin Resource Sharing restrictions, such as the errors that prevent to embed an external web page within a IFRAME element: Refused to display in a frame because it is set 'X-Frame-Options' to 'SAMEORIGIN' Or those preventing JavaScript  AJAX requests (XMLHttpRequest, Fetch API and so on) to send and/or retrieve data to external websites: XMLHttpRequest cannot load . Origin is not allowed by Access-Control-Allow-Origin ... And so on. The proxy has been designed to run within a Cloudflare Worker, which is freely available for up to 100.000 requests per day; this basically means that you can use this proxy to put any external web page within a element, and/or call a external API via AJAX, and/or to bypass any common CORS restriction without spending a penny,  assuming you don't have enterprise-grade service level requirements. Wait a minute... what is CORS? If you've stumbled upon this project there's a high chance you already know what CORS actually is and why you need to bypass such policies: if that's the case, just skip this section and go ahead. In the unlikely case you don't, just know that Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. Read the full article
0 notes