Initial commit

This commit is contained in:
Sergey Chernov 2022-11-11 00:22:26 +01:00
commit 8f950991a3
21 changed files with 3200 additions and 0 deletions

6
.gitignore vendored Normal file
View File

@ -0,0 +1,6 @@
# Project exclude paths
/.gradle/
/build/
/build/classes/kotlin/js/test/
/build/classes/kotlin/jvm/main/
/build/classes/kotlin/jvm/test/

19
README.md Normal file
View File

@ -0,0 +1,19 @@
# Superlogin utilities
> Work in progress, too early to use.
This project targets to provide command set of multiplatform tools to faciliate restore access with non-recoverable passwords by providing a backup `secret` string as the only way to reset the password.
This technology is required in the systems where user data are not disclosed to anybody else, as an attempt to allow lost password reset by mean of a `secret` string that could be kept somewhere in a safe place. It allows password and protected content updates to be recoverable with a `secret`.
It also contains useful tools for this type of application:
- `BackgroundKeyGeneretor` allows to accumulate the entropy from user events and perform ahead private key generation in the background (also in JS).
- `DerivedKeys` simplify processing passwords in a safe and smart manner.
- `AccessControlObject` to contain recoverable password-protected data with a backup `secret` word to restore access.
Will be published under MIT when become usable.

58
build.gradle.kts Normal file
View File

@ -0,0 +1,58 @@
plugins {
kotlin("multiplatform") version "1.7.20"
kotlin("plugin.serialization") version "1.7.20"
`maven-publish`
}
group = "net.sergeych"
version = "0.0.1-SNAPSHOT"
repositories {
mavenCentral()
mavenLocal()
maven("https://maven.universablockchain.com")
}
//configurations.all {
// resolutionStrategy.cacheChangingModulesFor(30, "seconds")
//}
kotlin {
jvm {
compilations.all {
kotlinOptions.jvmTarget = "1.8"
}
withJava()
testRuns["test"].executionTask.configure {
useJUnitPlatform()
}
}
js(IR) {
browser {
commonWebpackConfig {
cssSupport.enabled = true
}
}
}
sourceSets {
val commonMain by getting {
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.3")
api("net.sergeych:unikrypto:1.2.1-SNAPSHOT")
api("net.sergeych:parsec3:0.3.1-SNAPSHOT")
api("net.sergeych:boss-serialization-mp:0.2.4-SNAPSHOT")
3 }
}
val commonTest by getting {
dependencies {
implementation(kotlin("test"))
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.4")
}
}
val jvmMain by getting
val jvmTest by getting
val jsMain by getting
val jsTest by getting
}
}

4
gradle.properties Normal file
View File

@ -0,0 +1,4 @@
kotlin.code.style=official
kotlin.mpp.enableGranularSourceSetsMetadata=true
kotlin.native.enableDependencyPropagation=false
kotlin.js.generate.executable.default=false

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

234
gradlew vendored Executable file
View File

@ -0,0 +1,234 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

89
gradlew.bat vendored Normal file
View File

@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

2224
kotlin-js-store/yarn.lock Normal file

File diff suppressed because it is too large Load Diff

3
settings.gradle.kts Normal file
View File

@ -0,0 +1,3 @@
rootProject.name = "superlogin"

View File

@ -0,0 +1,156 @@
package net.sergeych.superlogin
import kotlinx.serialization.Serializable
import net.sergeych.boss_serialization_mp.BossEncoder
import net.sergeych.unikrypto.Container
import net.sergeych.unikrypto.DecryptingKey
import net.sergeych.unikrypto.Safe58
import net.sergeych.unikrypto.SymmetricKey
import kotlin.reflect.KType
import kotlin.reflect.typeOf
/**
* Access Control Object (ACO) allows to decrypt vital application data using either some `passwordKey`, usually
* obtained from user password using [DerivedKeys], or a special randomly created `secret` string, which is
* hard to remember but cryptographically string and contains some protection against typing errors,
* see [RestoreKey] for details. Once the access control object is generated, it can be decrypted using:
*
* - regenerated password key, usually [DerivedKeys.loginAccessKey]
* - `restoreSecret`, that should only be known to a user
*
* It is possible to change data and/or `passwordKey` of a decrypted object. Use [packed] property on new instance
* to save encrypted updated data.
*
* AceesControlObject holds also application-specific `data`.
*
* _Important note. While the primary constructor is public, we strongly recommend never using it directly.
* To construct it please use one of:_
*
* - [AccessControlObject.pack] to generate new
* - [AccessControlObject.unpackWithPasswordKey] to decrypt it with a password key
* - [AccessControlObject.unpackWithSecret] to decrypt it with a `secret`
*
* @param payloadType used to properly serialize application=specific data for [payload]
* @param packed encrypted and packed representation of the object, could be stored in public.
* @param passwordKey the password-derived key that could be used to unpack the [packed] data
* @param data contains necessary data to keep and operate the ACO
*/
class AccessControlObject<T>(
val payloadType: KType,
val packed: ByteArray,
val passwordKey: SymmetricKey,
val data: Data<T>,
) {
/**
* The application-specific data stored in the ACO. Should be @Serializable or a simple type
*/
val payload: T by data::payload
/**
* The ID that can be used to index/find the stored ACO, restoreId is derived from the secret
* with [RestoreKey] and could be obtanied by application software independently. The recommended
* use is to identify stored login record that should include a copy of most recent
* packed AccessControlObject.
*/
val restoreId: ByteArray by data::restoreId
/**
* Internal use only. The data ACO needs to operate, including the application's [payload]. This is
* the content of encrypted packed ACO.
*/
@Serializable
class Data<T>(
val restoreId: ByteArray,
val derivedRestoreKey: SymmetricKey,
val passwordKey: SymmetricKey,
val payload: T,
)
/**
* Update payload and return new instance of te ACO. The `secret` and `passwordKey` are not changed.
* Use [packed] property on the result to save updated copy.
*/
inline fun <reified R>updatePayload(newPayload: R): AccessControlObject<R> {
val data = Data(restoreId, data.derivedRestoreKey, passwordKey, newPayload)
return AccessControlObject<R>(
typeOf<Data<R>>(),
Container.encrypt(
data,
passwordKey, data.derivedRestoreKey
),
passwordKey, data
)
}
/**
* Update the password key and return new instance. It could be decrypted with the same `secret` and
* [newPasswordKey] only. The [payload] is not changed.
*/
fun updatePasswordKey(newPasswordKey: SymmetricKey): AccessControlObject<T> {
val data = Data(restoreId, data.derivedRestoreKey, newPasswordKey, payload)
return AccessControlObject(
payloadType,
Container.encryptData(
BossEncoder.encode(payloadType,data),
newPasswordKey, data.derivedRestoreKey
),
newPasswordKey, data
)
}
class WrongKeyException : Exception("can't decrypt AccessControlObject")
companion object {
/**
* Create and pack brand-new access control object with new random `secret`. It returns [RestoreKey]
* instance which contains not only `secret` but also `restoreId` which are often needed to save (and identify)
* encrypted object in the cloud, and also the key used to encrypt it. _Never save the key to disk or
* transmit it over the network_. If need, derive it from s `secret` again, see [RestoreKey.parse].
* @param passwordKey the second key that is normally used to decrypt ACO
* @param payload application-specific data to keep inside the ACO
* @return pair where first is a [RestoreKey] instance containing new `secret` and so on, and packed encrypted
* ACO that could be restored using `secret` or a [passwordKey]
*/
inline suspend fun <reified T> pack(
passwordKey: SymmetricKey,
payload: T,
): Pair<RestoreKey, ByteArray> {
val restoreKey = RestoreKey.generate()
return restoreKey to Container.encrypt(
Data(restoreKey.restoreId, restoreKey.key, passwordKey,payload),
passwordKey, restoreKey.key
)
}
/**
* Unpack and decrypt ACO with a password key
* @return decrypted ACO or null if the key is wrong.
*/
inline fun <reified T> unpackWithPasswordKey(packed: ByteArray, passwordKey: SymmetricKey): AccessControlObject<T>? =
Container.decrypt<Data<T>>(packed, passwordKey)?.let {
println(it)
AccessControlObject(typeOf<Data<T>>(), packed, passwordKey, it)
}
/**
* Unpack and decrypt ACO with a [secret]. If you want to check [secret] integrity, use
* [RestoreKey.checkSecretIntegrity].
* @return deccrypted ACO or null if the secret is wrong
*/
suspend inline fun <reified T> unpackWithSecret(packed: ByteArray, secret: String): AccessControlObject<T>? {
try {
val (id, key) = RestoreKey.parse(secret)
return Container.decrypt<Data<T>>(packed, key)?.let { data ->
AccessControlObject(typeOf<Data<T>>(), packed, data.passwordKey, data)
}
}
catch(_: RestoreKey.InvalidSecretException) {
return null
}
}
}
}

View File

@ -0,0 +1,101 @@
package net.sergeych.superlogin
import kotlinx.coroutines.Deferred
import kotlinx.datetime.Clock
import net.sergeych.mp_tools.globalDefer
import net.sergeych.unikrypto.*
import kotlin.random.Random
import kotlin.time.Duration.Companion.seconds
object BackgroundKeyGenerator {
const val DefaultStrength = 4096
class EntropyLowException : Exception("entropy level is below requested")
private var keyStrength = DefaultStrength
private var nextKey: Deferred<PrivateKey>? = null
var entropy = 0
private set
private val hashAlgorithm = HashAlgorithm.SHA3_256
private var entropyHash: ByteArray? = null
fun startPrivateKeyGeneration(strength: Int = DefaultStrength) {
if (keyStrength != strength) {
nextKey?.cancel()
nextKey = null
keyStrength = strength
}
nextKey = globalDefer { AsymmetricKeys.generate(keyStrength) }
}
fun getKeyAsync(strength: Int = DefaultStrength, startNext: Boolean = true): Deferred<PrivateKey> {
if (keyStrength != strength || nextKey == null)
startPrivateKeyGeneration(strength)
return nextKey!!.also {
nextKey = null
if (startNext) startPrivateKeyGeneration(strength)
}
}
suspend fun getPrivateKey(strength: Int = DefaultStrength): PrivateKey = getKeyAsync(strength).await()
fun addEntropyString(s: String, count: Int = 10) {
entropy += count
entropyHash = entropyHash?.let { hashAlgorithm.digest(s.encodeToByteArray(), it) } ?: hashAlgorithm.digest(s)
}
fun addEntropyPointerMove(x: Int, y: Int) {
addEntropyString("x:$x,y:$y")
}
private var lastTime = Clock.System.now()
fun addEntropyKey(key: String?) {
val t = Clock.System.now()
val e = (if (t - lastTime < 1.seconds) 3 else 10) + (key?.length ?: 0) * 4
addEntropyString("${Clock.System.now().nanosecondsOfSecond}$key", e)
lastTime = t
}
fun addEntropyTimestamp() {
addEntropyKey(null)
}
fun randomSymmetricKey(minEntropy: Int = 0): SymmetricKey {
return SymmetricKeys.create(randomBytes(32, minEntropy), BytesId.random()).also {
entropy = 0
addEntropyTimestamp()
}
}
fun randomBytes(length: Int,minEntropy: Int): ByteArray {
entropyHash?.let {
if (minEntropy <= entropy) {
entropy -= minEntropy
addEntropyTimestamp()
return randomBytes(length, it)
}
}
throw EntropyLowException()
}
fun randomBytes(length: Int, IV: ByteArray? = null): ByteArray {
var result = byteArrayOf()
var iv2 = IV ?: Random.nextBytes(32)
entropyHash?.let { iv2 += it }
var seed = HashAlgorithm.SHA3_384.digest(Random.nextBytes(48), iv2)
while (result.size < length) {
if (result.size + seed.size <= length)
result += seed
else
result += seed.sliceArray(0 until (length - result.size))
seed = HashAlgorithm.SHA3_384.digest(Random.nextBytes(48), seed)
}
return result
}
}

View File

@ -0,0 +1,21 @@
package net.sergeych.superlogin
import net.sergeych.unikrypto.SymmetricKey
/**
* Super creds are derived from a password and given derivatino parameters.
* They should not being sent over the netowkr as is or stored so it is not serializable.
*/
class DerivedKeys(
val loginId: ByteArray,
val loginAccessKey: SymmetricKey,
val systemAccessKey: SymmetricKey
) {
companion object {
suspend fun derive(password: String, params: PasswordDerivationParams = PasswordDerivationParams()): DerivedKeys {
val kk = params.derive(password, 3)
return DerivedKeys(kk[0].keyBytes, kk[1], kk[2])
}
}
}

View File

@ -0,0 +1,20 @@
package net.sergeych.superlogin
import kotlinx.serialization.Serializable
import net.sergeych.unikrypto.HashAlgorithm
import net.sergeych.unikrypto.Passwords
import net.sergeych.unikrypto.SymmetricKey
import kotlin.random.Random
@Serializable
class PasswordDerivationParams(
val rounds: Int = 15000,
val algorithm: HashAlgorithm = HashAlgorithm.SHA3_256,
val salt: ByteArray = Random.nextBytes(32),
) {
suspend fun derive(password: String,amount: Int = 1): List<SymmetricKey> {
return Passwords.deriveKeys(password, amount, rounds, algorithm, salt, Passwords.KeyIdAlgorithm.Independent)
}
}

View File

@ -0,0 +1,33 @@
package net.sergeych.superlogin
import net.sergeych.parsec3.Adapter
import net.sergeych.parsec3.WithAdapter
/**
* Registration instances are used to perform registration
* in steps to not no regemerate all keys on every attempt to
* say change login.
*/
class Registration<T: WithAdapter>(adapter: Adapter<T>) {
sealed class Result {
/**
* Login is already in use or is somehow else invalid
*/
object InvalidLogin: Result()
/**
* Operation failed for nknown reason, usually it means
* network or server downtime
*/
object NetworkFailure: Result()
// class Success(val l)
}
// fun register(
// login: String,
// password: String,
// )
}

View File

@ -0,0 +1,7 @@
package net.sergeych.superlogin
import kotlinx.serialization.Serializable
import net.sergeych.unikrypto.PrivateKey
import net.sergeych.unikrypto.SymmetricKey

View File

@ -0,0 +1,69 @@
package net.sergeych.superlogin
import net.sergeych.boss_serialization_mp.BossEncoder
import net.sergeych.unikrypto.*
/**
* RestoreKey is a specially constructed highly random string that produces cryptographically
* independent ID and symmetric key tohether with some tolerance to human typing errors and minimal
* integrity check to simplify its entry.
*
* The restore key is too long to remember, it should better be copied to some safe place.It is intended
* as a last resort to restore access to something impprtant using [AccessControlObject] object.
*
* Construct new instance with [generate], check with [checkSecretIntegrity] and derive key and id
* with [parse]
*/
class RestoreKey private constructor(
val restoreId: ByteArray,
val key: SymmetricKey,
val secret: String,
) {
class InvalidSecretException: Exception("secret is not valid")
companion object {
/**
* Remove auxiliary characters from secret
*/
private fun p(secret: String): String = secret.trim().replace("-", "")
/**
* Perform internal integrity check against occasional mistypes. This check does
* not mean it the key are ok to decrypt anything, just that the secret was not mistyped.
*
* This method does not alter key strength which is 136 random bits.
*/
fun checkSecretIntegrity(secret: String): Boolean {
return kotlin.runCatching { Safe58.decodeWithCrc(p(secret)) }.isSuccess
}
/**
* Parse the secret (secret key combination) and provide corresponding id and key to
* find and decrupt [AccessControlObject] object.
* @return restoreId to restoreKey pair
* @throws Safe58.InvalidCrcException if the secret is not valid, see [checkSecretIntegrity].
*/
suspend fun parse(secret: String): Pair<ByteArray, SymmetricKey> {
// Just ensure secret is valid
val s = p(secret)
if( !checkSecretIntegrity(s) ) throw InvalidSecretException()
return Passwords.deriveKeys(
s,
2,
salt = HashAlgorithm.SHA3_256.digest(s + "RestoreKeySecret"),
rounds = 1000
).let { (a, b) -> a.keyBytes to b }
}
/**
* Generate brand new random secret and return it and parsed id and key.
*/
suspend fun generate(): RestoreKey {
val secret = Safe58.encodeWithCrc(BackgroundKeyGenerator.randomBytes(17))
val (id, key) = parse(secret)
return RestoreKey(id, key, secret.chunked(5).joinToString("-"))
}
}
}

View File

@ -0,0 +1,14 @@
package net.sergeych.superlogin
import net.sergeych.parsec3.Adapter
class SuperloginClient(adapter: Adapter<*>) {
// init {
// adapter.invokeCommand()
// }
}

View File

@ -0,0 +1,61 @@
package net.sergeych.superlogin
import kotlinx.serialization.Serializable
import net.sergeych.parsec3.CommandHost
import net.sergeych.parsec3.WithAdapter
import net.sergeych.unikrypto.PublicKey
@Serializable
data class RegistrationArgs(
val loginName: String,
val loginId: ByteArray,
val loginPublicKey: PublicKey,
val derivationParams: PasswordDerivationParams,
val loginData: ByteArray,
val restoreId: ByteArray,
val restoreData: ByteArray,
val extraData: ByteArray? = null
)
@Serializable
sealed class AuthenticationResult {
@Serializable
data class Success(
val loginToken: ByteArray,
val extraData: ByteArray?
): AuthenticationResult()
@Serializable
object LoginUnavailable: AuthenticationResult()
@Serializable
object RestoreIdUnavailable: AuthenticationResult()
}
@Serializable
data class LoginArgs(
val loginId: ByteArray,
val packedSignedRecord: ByteArray
)
@Serializable
data class LoginData(
val encryptedPrivateKey: ByteArray,
val loginNonce: ByteArray
)
class SuperloginServerApi<T: WithAdapter> : CommandHost<T>() {
val registerUser by command<RegistrationArgs,AuthenticationResult>()
val loginUserByToken by command<ByteArray,AuthenticationResult>()
val requestUserLoginParams by command<String,PasswordDerivationParams>()
/**
* Get resstoreData by restoreId: password reset procedure start.
*/
val requestUserLogin by command<ByteArray,ByteArray>()
// val performLogin by command<LoginArgs
}

View File

@ -0,0 +1,48 @@
package superlogin
import kotlinx.coroutines.test.runTest
import net.sergeych.superlogin.AccessControlObject
import net.sergeych.superlogin.RestoreKey
import net.sergeych.unikrypto.SymmetricKeys
import kotlin.test.*
internal class AccessControlObjectTest {
@Test
fun createRestoreTest() = runTest {
val pk1 = SymmetricKeys.random()
val pk2 = SymmetricKeys.random()
val (rk, packed1) = AccessControlObject.pack(pk1, 117)
println(rk.secret)
val ac1 = AccessControlObject.unpackWithPasswordKey<Int>(packed1,pk1)
assertNotNull(ac1)
assertEquals(117, ac1.payload)
val ac2 = AccessControlObject.unpackWithSecret<Int>(packed1,rk.secret)
assertNotNull(ac2)
assertEquals(117, ac2.payload)
assertNull(AccessControlObject.unpackWithPasswordKey<Int>(packed1,pk2))
assertNull(AccessControlObject.unpackWithSecret<Int>(packed1,"the_-wrong-secret-yess"))
val (rk2, packed2) = AccessControlObject.pack(pk2, 107)
assertNull(AccessControlObject.unpackWithSecret<Int>(packed1,rk2.secret))
var ac21 = AccessControlObject.unpackWithPasswordKey<Int>(packed2,pk2)
assertNotNull(ac21)
assertEquals(107, ac21.payload)
var packed3 = ac1.updatePayload(121).packed
ac21 = AccessControlObject.unpackWithPasswordKey(packed3,pk1)
assertNotNull(ac21)
assertEquals(121, ac21.payload)
packed3 = ac1.updatePasswordKey(pk2).packed
println("-------")
ac21 = AccessControlObject.unpackWithPasswordKey(packed3,pk2)
assertNotNull(ac21)
assertEquals(117, ac21.payload)
ac21 = AccessControlObject.unpackWithSecret(packed3,rk.secret)
assertNotNull(ac21)
assertEquals(117, ac21.payload)
}
}

View File

@ -0,0 +1,28 @@
package superlogin
import kotlinx.coroutines.test.runTest
import net.sergeych.superlogin.RestoreKey
import kotlin.test.*
internal class RestoreKeyTest {
@Test
fun checkRestoreKey() = runTest {
val rk = RestoreKey.generate()
println(rk.secret)
println(rk.restoreId)
println(rk.key)
val (id, k) = RestoreKey.parse(rk.secret)
assertContentEquals(rk.restoreId, id)
assertEquals(rk.key.id, k.id)
assertContentEquals(rk.key.keyBytes, k.keyBytes)
val x = StringBuilder(rk.secret)
x[0] = (x[0].code xor 0x75).toChar()
assertFails {
RestoreKey.parse(x.toString())
}
}
}