ramsey/uuid - validate a name-based hashed has the name that we assign it to the uuid - slim

Any reliable uuid package from Packagist that I can download and use it for Slim framework?
Ideally,I would an uuid that I can hash a type, e.g. php, into the string. then i can check if that uuid has 'php'.
EDIT:
How can I validate a name-based hashed has the name that we assign it to the uuid?
// Generate a version 3 (name-based and hashed with MD5) UUID object
$uuid3 = Uuid::uuid3(Uuid::NAMESPACE_DNS, 'php.net');
$uuid = $uuid3->toString();
For instance:
if ($uuid3->getName($uuid) === 'php.net') {
// do something
}
Is this possible?

The best UUID package is https://github.com/ramsey/uuid
Just use composer require ramsey/uuid to install it.
Ideally,I would an uuid that I can hash a type, e.g. php, into the string. then i can check if that uuid has 'php'.
I don't understand this. UUIDs create a unique string. From Wikipedia:
A universally unique identifier (UUID) is a 128-bit number used to identify information in computer systems. The term globally unique identifier (GUID) is also used.
When generated according to the standard methods, UUIDs are for practical purposes unique, without depending for their uniqueness on a central registration authority or coordination between the parties generating them
Edit.
To answer your new question…
You can't reverse a hash, so you need to hash again and compare.
$uuid = Uuid::uuid3(Uuid::NAMESPACE_DNS, 'php.net')->toString();
$domainFromUser = 'example.com';
$userUuid = Uuid::uuid3(Uuid::NAMESPACE_DNS, $domainFromUser)->toString();
if ($uuid === $userUuid) {
// user provided the right domain
}

Related

Change encrypted data prefix of the Transit secret engine

The transit secrets engine returns encrypted data with a prefix:
% vault write transit/encrypt/my-key plaintext=$(base64 <<< "my secret data")
Key Value
ciphertext vault:v1:C7BqsulaJTww6+zyO+0TnjFUUdDVTQWIatlbxOtEkZbF5govTZAp8S6gjQ==
Is there any way of customazation where we can change vault:v1: >>>> CMPname:APP:
vault:v2:VHTTBb2EyyNYHsa3XiXsvXOQSLKulH+NqS4eRZdtc2TwQCxqJ7PUipvqQ==
So that it becomes:
CompnanyName:appV1:0VHTTBb2EyyNYHsa3XiXsvXOQSLKulH+NqS4eRZdtc2TwQCxqJ7PUipvqQ==
Vault has a default version template that evaluates to vault:v{{version}}. There is code that support a custom version template, but the version_template parameter is ignored when you create the key.
So as of today, this option does not exist, sorry.
This metadata is not encrypted (nor signed). I suggest you either add a prefix to it:
CompnanyName:app:vault:v1:0VHTTBb2EyyNYHsa3XiXsvXOQSLKulH+NqS4eRZdtc2TwQCxqJ7PUipvqQ=
Or replace it:
CompnanyName:app:v1:0VHTTBb2EyyNYHsa3XiXsvXOQSLKulH+NqS4eRZdtc2TwQCxqJ7PUipvqQ=
To be future proof (so that you can remove your custom code and use version_template one day), I suggest that you keep a link between my-key (the name of the key) and the prefix. As the code stands today, it is unlikely that Vault will support multiple prefixes for a single key name.

Hashing payload data when adding a new user in a Facebook Custom Audiences

i need an help with the API to add a user in a custom audience.
Looking at the doc it seems not clear if it has to be hashed every single attribute of the payload.data key or not.
On the documentation (https://developers.facebook.com/docs/marketing-api/reference/custom-audience/users/v2.9) it seems like the hash in not required but in this other article (https://developers.facebook.com/docs/marketing-api/audiences-api) seems like each one of them has to be hashed.
Any thoughts?
Yes, you need to hash everything apart from external identifiers, see this part of the doc:
You must hash your data as SHA256; we don't support other hashing
mechanisms. This is required for all data except External Identifiers.
Before hashing, normalize your data. Only First name FN and Last Name
LN support special characters and non-Roman alphabet. For best match
results, provide the Roman alphabet translation with no special
characters.
External identifiers are just extern_id which isn't applicable to most people anyway.
I'd recommend using one our our SDKs if possible as we handle all of the hashing for you. For example:
use FacebookAds\Object\CustomAudienceMultiKey;
use FacebookAds\Object\Fields\CustomAudienceMultikeySchemaFields;
$users = array(
array('ExternId123', 'FirstName', 'test2#example.com', 'LastName1'),
array('ExternId456', 'FirstNameTest', '', 'LastNameTest'),
array('ExternId789', '', 'test3#example.com', 'LastNameTest'),
);
$schema = array(
CustomAudienceMultikeySchemaFields::EXTERN_ID,
CustomAudienceMultikeySchemaFields::FIRST_NAME,
CustomAudienceMultikeySchemaFields::EMAIL,
CustomAudienceMultikeySchemaFields::LAST_NAME,
);
$audience = new CustomAudienceMultiKey('<CUSTOM_AUDIENCE_ID>');
$audience->addUsers($users, $schema);

Manually insert TURN users (Coturn) into a database

I'm trying to set up a TURN server for a project using Coturn but am finding that documentation is sketchy at best...
I realise that there is a turnadmin tool that will do this for you, but I would greatly prefer to just run queries on my database directly. This is an app with potentially many users and their shared keys (hmackey in turnusers_lt) are subject to change (in order to not share passwords with the app the app uses a 'fake' password which is a hash of certain volatile user parameters that aren't so secret).
I can gather from the scant docs that the hmackey is computed using the realm, username and password:
$ turnadmin -k -u myusername -r my.realm.org -p my-password
> e.g. 0x7a69b0e2b747a4560045f79d171b78c0
Given that my code will know these three parameters, how do I build the hmac hash? E.g. in PHP I have
string hash_hmac ( string $algo , string $data , string $key [, bool $raw_output = false ] )
$algo here should be SHA1, but what values would go into $data (e.g. concat of user/pass) and $key (e.g. realm)?
There's also a turn_secret table listing a 'value' for a realm, I was guessing this should be used as the $key in the above example, but adding and modifying the keys still give the same result when I call turnadmin.
Essentially, what I want to do is (pseudo-code):
// user registers
// pseudo-code, this is of course computed using php's password_hash function
$hashed_pw = hash($pw);
$db->query('insert into usertable (name, pass) values ($name, $hashed_pw)');
// this is implemented somewhere...
$coturn_pw = get_secret_hash($name);
// this needs implementing...
$HAMC = calc_hmac($name, $coturn_pw, 'my.realm.com');
$turndb->query('insert into turnusers_lt values (...)');
// on update, delete also update turnusers_lt
...and then in the client, I should now be able to connect to the TURN server using $name and $coturn_pw as credentials for my.realm.com.
Or am I over-thinking this and should I just use a generic user for my app, hardcode the password and let Coturn figure out who is talking to who?
How to build the HMAC key is described in RFC 5389:
key = MD5(username ":" realm ":" SASLprep(password))
where MD5 is defined in RFC 1321 and SASLprep() is defined in RFC 4013
The only table you need to update is turnusers_lt. The turn_secret table and SHA1 algorithm is used for generating time-limited credentials.
INSERT INTO turnusers_lt (realm, name, hmackey) VALUES (:realm, :username, :key);
And of course, use prepared statements rather than building the SQL string manually.
OrangeDog answer is correct.
With node.js:
const crypto= require("crypto");
const username= "foo";
const realm= "here";
const password= "secret";
const hmac = crypto
.createHash("md5")
.update(`${username}:${realm}:${password}`)
.digest("hex")
;

Reference for Constants.ClaimTypes

I've got IdentityServer3 running as a standalone identity server.
I have a separate MVC client that uses Cookies and OpenIdConnect for authentication. I'm trying to set up claims transformations amongst other things, and would like to reference the different claims types like so:
var givenName = id.FindFirst(Constants.ClaimTypes.GivenName);
var familyName = id.FindFirst(Constants.ClaimTypes.FamilyName);
var sub = id.FindFirst(Constants.ClaimTypes.Subject);
var roles = id.FindAll(Constants.ClaimTypes.Role);
On the IdentityServer3, I reference these using Thinktecture.IdentityServer.Core.Constants however on my MVC client I don't think I should need to reference Thinktecture.IdentityServer3 just for these string constants? Is there a client library that is recommended to be used in this case? I've tried Thinktecture.IdentityModel and some .NET references but none seem to replicate the ClaimTypes in Thinktecture.IdentityServer.Core.Constants. The best I've found is System.Security.Claims.ClaimTypes but that seems to have several missing e.g. FamilyName.
The first placed I looked was Thinktecture.IdentityModel but was surprised these aren't there.
So what's the magic reference? Or is it appropriate to load Thinktecture.IdentityServer3 just for these strings?
Thanks
EDIT: So I've found Thinktecture.IdentityModel.Client which contains a JwtClaimTypes that seems to mirror ClaimTypes. Why is this named with a Jwt prefix though?
The IdentityServer ClaimType constants are just a map of the OpenID Connect standard claims.
You'd be best off making your own class for these constants, as you said there's no point pulling in the full Identity Server 3 package and I don't think they are available in any other packages...
Do note that the claims come across via JSON in the JWT as snake case. For example FamilyName will be family_name.
You can install the Microsoft.AspNetCore.Authentication.JwtBearer package. It includes the JwtRegisteredClaimNames struct which you can use like:
using static Microsoft.IdentityModel.JsonWebTokens.JwtRegisteredClaimNames;
â‹®
var userId = User.FindFirstValue(Sub);
Agree with Scott Brady, the best way to go about this is to create your constants class. We have created a shared library for this purpose, which contains claim type constants and have used them both in the server and the client projects.
NB: Apart from 'id_token' and 'sub' claim types, you can use your custom claim types in the implementation of 'IUserService'. This gives better clarity to claim type names also as you can use specific names based on your implementation.
Use IdentityModel
I've seen people use bare strings like "sub", but why, when the constants exist?
namespace IdentityModel
{
/// <summary>Commonly used claim types</summary>
public static class JwtClaimTypes
{
/// <summary>Unique Identifier for the End-User at the Issuer.</summary>
public const string Subject = "sub";
/// <summary>End-User's full name in displayable form including all name parts, possibly including titles and suffixes, ordered according to the End-User's locale and preferences.</summary>
public const string Name = "name";
/// <summary>Given name(s) or first name(s) of the End-User. Note that in some cultures, people can have multiple given names; all can be present, with the names being separated by space characters.</summary>
public const string GivenName = "given_name";
/// <summary>Surname(s) or last name(s) of the End-User. Note that in some cultures, people can have multiple family names or no family name; all can be present, with the names being separated by space characters.</summary>
public const string FamilyName = "family_name";

How to use strong encryption for password field using grails with postgresql database?

I had to migrate a legacy database with clear text password to a PostgresSQL database. I've looked up what's the best way to encrypt password in a database and found the pgcrypto extension with slow algorithm. (see pgcrypto documentation for 8.4)
The migration is done for data and everything is working well.
Now I have to write a CRUD application to handle this data.
I'm wondering what's the best way to use this strong encryption with grails ?
In my model, I've used the afterInsert event to handle this :
def afterInsert() {
Compte.executeUpdate("update Compte set hashpass=crypt(hashpass, gen_salt('bf', 8)) where id = (:compteId)", [compteId: this.id])
}
I guess that I should also check if the hashpass field is modified whenever the model is saved. But before that, is there another (best) way to achieve my goal ?
Edit : I cannot use the Spring Security bcrypt plugin here. The CRUD application that I'm writing use SSO CAS so I don't need such a plugin. The CRUD application manages accounts for another application that I don't own. I just need to create a new account, modify or delete an existing one. This is very simple. The tricky part is to hack grails so that it takes into account the password field and use a specific sql to store it to a postgreSQL database.
Edit 2 :
I've come up with the following code but it doesn't work
def beforeInsert() {
hashpass = encodePassword(hashpass);
}
def encodePassword(cleartextpwd) {
// create a key generator based upon the Blowfish cipher
KeyGenerator keygenerator = KeyGenerator.getInstance("Blowfish");
// create a key
SecretKey secretkey = keygenerator.generateKey();
// create a cipher based upon Blowfish
Cipher cipher = Cipher.getInstance(ALGORITHM);
// initialise cipher to with secret key
cipher.init(Cipher.ENCRYPT_MODE, secretkey);
// get the text to encrypt
String inputText = cleartextpwd;
// encrypt message
byte[] encrypted = cipher.doFinal(inputText.getBytes("UTF-8"));
return Base64.encodeBase64String(encrypted);
}
I get a hash that is not a blowfish hash (beginning with $2a$08$ )
Edit 3 :
I've finally came up with a cleaner grails solution after reading this wiki page : grails.org/Simple+Dynamic+Password+Codec (not enough reputation to put more than 2 links so add http:// before) and the bug report jira.grails.org/browse/GRAILS-3620
Following advice from #lukelazarovic, I've also used the algorithm from the spring security plugin.
Here is my password encoder to put into grails/utils :
import grails.plugin.springsecurity.authentication.encoding.BCryptPasswordEncoder;
class BlowfishCodec {
static encode(target) {
// TODO need to put the logcount = 8 in configuration file
return new BCryptPasswordEncoder(8).encodePassword(
target, null)
}
}
I've updated my Compte model to call my password encoder before saving / updating the data :
def beforeInsert() {
hashpass = hashpass.encodeAsBlowfish();
}
def beforeUpdate() {
if(isDirty('hashpass')) {
hashpass = hashpass.encodeAsBlowfish();
}
}
The tricky part is to hack grails so that it takes into account the
password field and use a specific sql to store it to a postgreSQL
database.
Is there any particular reason to do the hashing in database?
IMHO it's better to hash the password in Grails, therefore have a code that is not database-specific and easier to read.
For hashing passwords using Blowfish algorithm using Java or Groovy see Encryption with BlowFish in Java
The resulting hash begins with algorithm specification, iteration count and salt, separated with dollar sign - '$'. So the hash may look like "$2a$08$saltCharacters" where 2a is a algorithm, 08 is iteration count, then follows salt and after salt is the hash itself.
For broader explanation see http://www.techrepublic.com/blog/australian-technology/securing-passwords-with-blowfish. Don't mind that it concerns to Blowfish in PHP, the principles applies for Java or Groovy as well.