replace ornicar.scalalib.Random with lila.common.Random

pull/9256/head
Niklas Fiekas 2021-06-24 13:08:23 +02:00
parent 58b3a48c27
commit 33d9d64c3a
15 changed files with 55 additions and 53 deletions

View File

@ -4,6 +4,8 @@ import lila.user.User
import org.joda.time.DateTime
import lila.common.SecureRandom
case class Student(
_id: Student.Id, // userId:clasId
userId: User.ID,
@ -50,10 +52,9 @@ object Student {
private[clas] object password {
private val random = new java.security.SecureRandom()
private val chars = ('2' to '9') ++ (('a' to 'z').toSet - 'l') mkString
private val nbChars = chars.length
private def secureChar = chars(random nextInt nbChars)
private def secureChar = chars(SecureRandom nextInt nbChars)
def generate =
User.ClearPassword {

View File

@ -1,6 +1,5 @@
package lila.common
import ornicar.scalalib.Random
import play.api.mvc._
import scala.concurrent.ExecutionContext
@ -12,7 +11,7 @@ final class LilaCookie(domain: NetDomain, baker: SessionCookieBaker) {
def makeSessionId(implicit req: RequestHeader) = session(LilaCookie.sessionId, generateSessionId())
def generateSessionId() = Random secureString 22
def generateSessionId() = SecureRandom nextString 22
def session(name: String, value: String)(implicit req: RequestHeader): Cookie =
withSession { s =>

View File

@ -1,12 +1,10 @@
package lila.common
import ornicar.scalalib.Random
case class Nonce(value: String) extends AnyVal with StringValue {
def scriptSrc = s"'nonce-$value'"
}
object Nonce {
def random: Nonce = Nonce(Random.secureString(24))
def random: Nonce = Nonce(SecureRandom.nextString(24))
}

View File

@ -2,9 +2,8 @@ package lila.common
import scala.collection.mutable.StringBuilder
object ThreadLocalRandom {
import java.util.concurrent.ThreadLocalRandom.current
abstract class Random {
protected def current: java.util.Random
def nextBoolean(): Boolean = current.nextBoolean()
def nextBytes(bytes: Array[Byte]): Unit = current.nextBytes(bytes)
@ -14,21 +13,31 @@ object ThreadLocalRandom {
def nextInt(n: Int): Int = current.nextInt(n)
def nextLong(): Long = current.nextLong()
def nextGaussian(): Double = current.nextGaussian()
def nextChar(): Char = {
val i = nextInt(62)
if (i < 26) i + 65
else if (i < 52) i + 71
else i - 4
}.toChar
def shuffle[T, C](xs: IterableOnce[T])(implicit bf: scala.collection.BuildFrom[xs.type, T, C]): C =
new scala.util.Random(current).shuffle(xs)
private def nextAlphanumeric(): Char = {
val chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
chars charAt nextInt(chars.length) // Constant time
}
def nextString(len: Int): String = {
val sb = new StringBuilder(len)
for (_ <- 0 until len) sb += nextChar()
for (_ <- 0 until len) sb += nextAlphanumeric()
sb.result()
}
def shuffle[T, C](xs: IterableOnce[T])(implicit bf: scala.collection.BuildFrom[xs.type, T, C]): C =
new scala.util.Random(current).shuffle(xs)
def oneOf[A](vec: Vector[A]): Option[A] =
vec.nonEmpty ?? {
vec lift nextInt(vec.size)
}
}
object ThreadLocalRandom extends Random {
override def current = java.util.concurrent.ThreadLocalRandom.current
}
object SecureRandom extends Random {
override val current = new java.security.SecureRandom().pp("init secure random")
}

View File

@ -15,7 +15,7 @@ case class AssetVersion(value: String) extends AnyVal with StringValue
object AssetVersion {
var current = random
def change() = { current = random }
private def random = AssetVersion(ornicar.scalalib.Random secureString 6)
private def random = AssetVersion(SecureRandom nextString 6)
}
case class IsMobile(value: Boolean) extends AnyVal with BooleanValue

View File

@ -1,8 +1,7 @@
package lila.fishnet
import ornicar.scalalib.Random
import com.gilt.gfc.semver.SemVer
import lila.common.IpAddress
import lila.common.{ IpAddress, SecureRandom }
import scala.util.{ Failure, Success, Try }
import org.joda.time.DateTime
@ -98,5 +97,5 @@ object Client {
}
}
def makeKey = Key(Random.secureString(8))
def makeKey = Key(SecureRandom.nextString(8))
}

View File

@ -4,9 +4,8 @@ import scala.concurrent.duration._
import chess.{ Black, Clock, White }
import lila.common.Future
import lila.common.{ Future, ThreadLocalRandom }
import lila.game.{ Game, GameRepo, UciMemo }
import ornicar.scalalib.Random.approximately
final class FishnetPlayer(
redis: FishnetRedis,
@ -43,7 +42,7 @@ final class FishnetPlayer(
sleep = (delay * accel) atMost 500
if sleep > 25
millis = sleep * 10
randomized = approximately(0.5f)(millis)
randomized = millis + millis * (ThreadLocalRandom.nextDouble() - 0.5)
divided = randomized / (if (g.turns > 9) 1 else 2)
} yield divided.millis

View File

@ -1,9 +1,8 @@
package lila.game
import chess.Color
import java.security.SecureRandom
import ornicar.scalalib.Random
import lila.common.{ ThreadLocalRandom, SecureRandom }
import lila.db.dsl._
final class IdGenerator(gameRepo: GameRepo)(implicit ec: scala.concurrent.ExecutionContext) {
@ -32,16 +31,15 @@ final class IdGenerator(gameRepo: GameRepo)(implicit ec: scala.concurrent.Execut
object IdGenerator {
private[this] val secureRandom = new SecureRandom()
private[this] val whiteSuffixChars = ('0' to '4') ++ ('A' to 'Z') mkString
private[this] val blackSuffixChars = ('5' to '9') ++ ('a' to 'z') mkString
def uncheckedGame: Game.ID = lila.common.ThreadLocalRandom nextString Game.gameIdSize
def uncheckedGame: Game.ID = ThreadLocalRandom nextString Game.gameIdSize
def player(color: Color): Player.ID = {
// Trick to avoid collisions between player ids in the same game.
val suffixChars = color.fold(whiteSuffixChars, blackSuffixChars)
val suffix = suffixChars(secureRandom nextInt suffixChars.length)
Random.secureString(Game.playerIdSize - 1) + suffix
val suffix = suffixChars(SecureRandom nextInt suffixChars.length)
SecureRandom.nextString(Game.playerIdSize - 1) + suffix
}
}

View File

@ -3,6 +3,7 @@ package lila.oauth
import org.joda.time.DateTime
import reactivemongo.api.bson._
import lila.common.SecureRandom
import lila.user.User
case class AccessToken(
@ -28,7 +29,7 @@ object AccessToken {
def isPersonal = value.lengthIs == idSize
}
def makeId = Id(ornicar.scalalib.Random secureString idSize)
def makeId = Id(SecureRandom nextString idSize)
case class ForAuth(userId: User.ID, scopes: List[OAuthScope])

View File

@ -5,7 +5,6 @@ import cats.data.Validated
import com.roundeights.hasher.Algo
import io.lemonlabs.uri.AbsoluteUrl
import org.joda.time.DateTime
import ornicar.scalalib.Random
import play.api.libs.json._
import lila.user.User

View File

@ -2,6 +2,7 @@ package lila.oauth
import org.joda.time.DateTime
import lila.common.SecureRandom
import lila.user.User
import io.lemonlabs.uri.AbsoluteUrl
@ -21,8 +22,8 @@ object OAuthApp {
case class Id(value: String) extends AnyVal
case class Secret(value: String) extends AnyVal
def makeId = Id(ornicar.scalalib.Random secureString 16)
def makeSecret = Secret(ornicar.scalalib.Random secureString 32)
def makeId = Id(SecureRandom nextString 16)
def makeSecret = Secret(SecureRandom nextString 32)
object BSONFields {
val clientId = "client_id"

View File

@ -6,7 +6,8 @@ import cats.data.Validated
import play.api.libs.json.Json
import com.roundeights.hasher.Algo
import io.lemonlabs.uri.AbsoluteUrl
import ornicar.scalalib.Random
import lila.common.SecureRandom
object Protocol {
case class Secret(value: String) {
@ -19,7 +20,7 @@ object Protocol {
override def hashCode = hashed.hashCode()
}
object Secret {
def random(prefix: String) = Secret(s"$prefix${Random.secureString(32)}")
def random(prefix: String) = Secret(s"$prefix${SecureRandom.nextString(32)}")
}
case class AuthorizationCode(secret: Secret) extends AnyVal

View File

@ -1,7 +1,6 @@
package lila.security
import org.joda.time.DateTime
import ornicar.scalalib.Random
import play.api.data._
import play.api.data.Forms._
import play.api.data.validation.{ Constraint, Valid => FormValid, Invalid, ValidationError }
@ -12,7 +11,7 @@ import reactivemongo.api.ReadPreference
import scala.annotation.nowarn
import scala.concurrent.duration._
import lila.common.{ ApiVersion, EmailAddress, HTTPRequest, IpAddress }
import lila.common.{ ApiVersion, EmailAddress, HTTPRequest, IpAddress, SecureRandom }
import lila.db.BSON.BSONJodaDateTimeHandler
import lila.db.dsl._
import lila.oauth.{ AccessToken, OAuthScope, OAuthServer }
@ -94,7 +93,7 @@ final class SecurityApi(
userRepo mustConfirmEmail userId flatMap {
case true => fufail(SecurityApi MustConfirmEmail userId)
case false =>
val sessionId = Random secureString 22
val sessionId = SecureRandom nextString 22
if (tor isExitNode HTTPRequest.ipAddress(req)) logger.info(s"Tor login $userId")
store.save(sessionId, userId, req, apiVersion, up = true, fp = none) inject sessionId
}
@ -102,7 +101,7 @@ final class SecurityApi(
def saveSignup(userId: User.ID, apiVersion: Option[ApiVersion], fp: Option[FingerPrint])(implicit
req: RequestHeader
): Funit = {
val sessionId = lila.common.ThreadLocalRandom nextString 22
val sessionId = SecureRandom nextString 22
store.save(s"SIG-$sessionId", userId, req, apiVersion, up = false, fp = fp)
}
@ -211,7 +210,7 @@ final class SecurityApi(
sessionId.startsWith(prefix) ?? store.getIfPresent(sessionId)
def saveAuthentication(userId: User.ID)(implicit req: RequestHeader): Fu[SessionId] = {
val sessionId = s"$prefix${Random secureString 22}"
val sessionId = s"$prefix${SecureRandom nextString 22}"
store.put(sessionId, userId)
logger.info(s"Appeal login by $userId")
fuccess(sessionId)

View File

@ -1,11 +1,11 @@
package lila.user
import java.security.SecureRandom
import java.util.Base64
import javax.crypto.Cipher
import javax.crypto.spec.{ IvParameterSpec, SecretKeySpec }
import com.roundeights.hasher.Implicits._
import lila.common.SecureRandom
import lila.common.config.Secret
/** Encryption for bcrypt hashes.
@ -54,14 +54,13 @@ final private class PasswordHasher(
import org.mindrot.BCrypt
import User.ClearPassword
private val prng = new SecureRandom()
private val aes = new Aes(secret)
private def bHash(salt: Array[Byte], p: ClearPassword) =
hashTimer(BCrypt.hashpwRaw(p.value.sha512, 'a', logRounds, salt))
def hash(p: ClearPassword): HashedPassword = {
val salt = new Array[Byte](16)
prng.nextBytes(salt)
SecureRandom.nextBytes(salt)
HashedPassword(salt ++ aes.encrypt(Aes.iv(salt), bHash(salt, p)))
}

View File

@ -1,12 +1,13 @@
package lila.user
import org.apache.commons.codec.binary.Base32
import reactivemongo.api.bson._
import java.security.SecureRandom
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import java.nio.ByteBuffer
import org.apache.commons.codec.binary.Base32
import reactivemongo.api.bson._
import lila.common.SecureRandom
import User.TotpToken
case class TotpSecret(secret: Array[Byte]) extends AnyVal {
@ -45,13 +46,11 @@ object TotpSecret {
"0" * (6 - s.length) + s
}
private[this] val secureRandom = new SecureRandom()
def apply(base32: String) = new TotpSecret(new Base32().decode(base32))
def random: TotpSecret = {
val secret = new Array[Byte](20)
secureRandom.nextBytes(secret)
SecureRandom.nextBytes(secret)
TotpSecret(secret)
}