Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
Authentication Security – RUBYSPB
Search
Sergey Nartimov
September 21, 2013
Programming
210
2
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Authentication Security – RUBYSPB
Sergey Nartimov
September 21, 2013
More Decks by Sergey Nartimov
See All by Sergey Nartimov
PubSub at Rails
lest
0
150
Rails in production - RubyConfBY 22 Mar 2015
lest
1
170
Sequel - BRUG 21 Feb 2015
lest
0
110
Elixir – Belarus Ruby User Group 25 Jan 2014
lest
3
680
Geospatial applications on Rails
lest
8
450
Design patterns – Belarus Ruby on Rails User Group 23 Feb 2013
lest
8
680
Ruby Stdlib – Minsk.rb October 2012
lest
10
430
Background jobs with realtime results – RailsClub'Moscow 2012
lest
5
240
Other Decks in Programming
See All in Programming
残高管理から台帳サービスへの進化
artoy
1
210
Railsバージョンを4倍にした話
optim
0
480
Optunaを作ったときにやりたかったこと、その後 (2026/10/16, Optuna Meetup #3)
iwiwi
2
1.1k
Lambda durable functionsでHuman in the Loopを楽に…楽に……
har1101
0
150
パスワード再設定メールのURLについて知っておこう
uyuki234
0
170
気持ちぃ〜角丸 Squircle
ryu1013
0
320
Agents on Rails - Rails at Scale 2026
irinanazarova
0
570
ChromeでローカルLLM
ryu1013
0
150
[Rails World 2026] Durable orchestration on Rails: from continuation to workflow
palkan
1
830
Kotlinize Is Not Just Converting to Kotlin
chigichan24
1
170
Simple Storage Service(S3) is not simple
iwatsukayura
0
300
Apple Intelligence を用いた個人情報誤送信防止、及びユーザーリクエスト体験の改善について
yukiny
0
360
Featured
See All Featured
Accessibility Awareness
sabderemane
1
250
Exploring the Power of Turbo Streams & Action Cable | RailsConf2023
kevinliebholz
37
6.6k
Learning to Love Humans: Emotional Interface Design
aarron
275
41k
A better future with KSS
kneath
240
18k
Designing Experiences People Love
moore
143
24k
Are puppies a ranking factor?
jonoalderson
2
4.1k
Measuring Dark Social's Impact On Conversion and Attribution
stephenakadiri
2
310
Building Better People: How to give real-time feedback that sticks.
wjessup
371
20k
HTML-Aware ERB: The Path to Reactive Rendering @ RubyCon 2026, Rimini, Italy
marcoroth
5
830
SERP Conf. Vienna - Web Accessibility: Optimizing for Inclusivity and SEO
sarafernandez
2
1.6k
Typedesign – Prime Four
hannesfritz
42
3.2k
What the history of the web can teach us about the future of AI
inesmontani
PRO
2
750
Transcript
Безопасность аутентификации веб-приложений Сергей Нартымов Brainspec https://github.com/lest twitter: @just_lest
None
Хэш с солью
None
Хэш с солью create_table :users do |t| t.string :name t.string
:salt t.string :hashed_password end
Хэш с солью def self.encrypted_password(password, salt) string_to_hash = password +
"wibble" + salt Digest::SHA1.hexdigest(string_to_hash) end def create_new_salt self.salt = self.object_id.to_s + rand.to_s end
Хэш с солью def password=(pwd) @password = pwd return if
pwd.blank? create_new_salt self.hashed_password = User.encrypted_password(self.password, self.salt) end
Хэш с солью def self.authenticate(name, password) user = self.find_by_name(name) if
user expected_password = encrypted_password(password, user.salt) if user.hashed_password != expected_password user = nil end end user end
has_secure_password
create_table :users do |t| t.string :name t.string :password_digest end class
User < ActiveRecord::Base has_secure_password end
user = User.new(name: "david") user.password = "mUc3m00RsqyRe" user.password_digest # =>
"$2a$10$4LEA7r4YmNHtvlAvHhsYAeZmk/ xeUVtMTYqwIvYY76EW5GUqDiP4." user.save user.authenticate("notright") # => false user.authenticate("mUc3m00RsqyRe") # => user
bcrypt
bcrypt $2a$10$vI8aWBnW3fID.ZQ4/z идентификатор алгоритма
bcrypt $2a$10$vI8aWBnW3fID.ZQ4/zo1G сложность
bcrypt $2a$10$vI8aWBnW3fID.ZQ4/zo1G.q1lRps соль
bcrypt o1G.q1lRps.9cGLcZEiGDMVr5yUP1KUOYTa
bcrypt def password=(unencrypted_password) unless unencrypted_password.blank? @password = unencrypted_password cost =
ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine::DEFAULT_COST self.password_digest = BCrypt::Password.create(unencrypted_password, cost: cost) end end def authenticate(unencrypted_password) BCrypt::Password.new(password_digest) == unencrypted_password && self end
bcrypt def password=(unencrypted_password) unless unencrypted_password.blank? @password = unencrypted_password cost =
ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine::DEFAULT_COST self.password_digest = BCrypt::Password.create(unencrypted_password, cost: cost) end end def authenticate(unencrypted_password) BCrypt::Password.new(password_digest) == unencrypted_password && self end
bcrypt
PBKDF2 scrypt bcrypt
PBKDF2 scrypt bcrypt
Инвалидация сессии
Инвалидация сессии user = User.authenticate(params[:name], params[:password]) if user session[:user_id] =
user.id redirect_to(:action => "index") else flash.now[:notice] = "Invalid user/password combination" end
Инвалидация сессии • хранить в сессии данные, которые изменяются при
изменении пароля • например, соль пароля (так делает devise)
Инвалидация сессии def serialize_into_session(record) [record.to_key, record.authenticatable_salt] end def authenticatable_salt encrypted_password[0,29]
if encrypted_password end
Блокировка доступа
Блокировка доступа • для пользователя • для IP-адреса
Блокировка доступа • CAPTCHA • разблокировка по ссылке из письма
Запомнить меня
Запомнить меня • добавляем токен и время • храним токен
в HttpOnly cookie
Запомнить меня def remember_me!(extend_period=false) self.remember_token = self.class.remember_token if generate_remember_token? self.remember_created_at
= Time.now.utc if generate_remember_timestamp?(extend_period) save(:validate => false) if self.changed? end
Запомнить меня cookies.signed[remember_key(resource, scope)] = remember_cookie_values(resource) def remember_cookie_values(resource) options =
{ :httponly => true } # ... options.merge!( :value => resource.class.serialize_into_cookie(resource), :expires => resource.remember_expires_at ) end
Перебор пользователей
• Неверный адрес e-mail или пароль. • Если ваш адрес
e-mail есть в нашей базе данных, то в течение нескольких минут вы получите письмо с инструкциями по восстановлению вашего пароля.
Тайминговые атаки
Тайминговые атаки def authenticate! resource = valid_password? && mapping.to.find_for_database_authentication(authentication_hash) return
fail(:not_found_in_database) unless resource if validate(resource){ resource.valid_password?(password) } resource.after_database_authentication success!(resource) end end
Тайминговые атаки user = User.last Benchmark.realtime { user.valid_password?('lolwut') } #
=> 0.321346
Восстановление пароля • не стоит генерировать пароль и присылать его
на почту • лучше генерировать токен и отправлять ссылку, по которой можно задать новый пароль
Сложность пароля
Сложность пароля validates :password, length: { minimum: 5, maximum: 20
}
SSL
SSL startssl.com
Двухэтапная аутентификация
Google Двухэтапная аутентификация
Google Facebook Двухэтапная аутентификация
Google Facebook Dropbox Двухэтапная аутентификация
Google Facebook AWS Dropbox Двухэтапная аутентификация
Google Facebook AWS Dropbox GitHub Двухэтапная аутентификация
Open Web Application Security Project • https://www.owasp.org/ • https://www.owasp.org/index.php/ Cheat_Sheets
Спасибо https://github.com/lest twitter: @just_lest Сергей Нартымов Brainspec