GithubHelp home page GithubHelp logo

cedarcode / cose-ruby Goto Github PK

View Code? Open in Web Editor NEW
15.0 4.0 10.0 292 KB

Ruby implementation of RFC 8152 CBOR Object Signing and Encryption (COSE)

Home Page: https://rubygems.org/gems/cose

License: MIT License

Ruby 99.76% Shell 0.24%
cose ruby cbor cose-key signing rfc

cose-ruby's Introduction

cose-ruby

Ruby implementation of RFC 8152 CBOR Object Signing and Encryption (COSE)

Gem Actions Build

Installation

Add this line to your application's Gemfile:

gem 'cose'

And then execute:

$ bundle

Or install it yourself as:

$ gem install cose

Usage

Key Objects

Deserialization (from CBOR to Ruby objects)

cbor_data = "..."

key = COSE::Key.deserialize(cbor_data)

Once you have a COSE::Key instance you can either access key parameters directly and/or convert it to an OpenSSL::PKey::PKey instance (if supported for the key type) for operating with it (encrypting/decrypting, signing/verifying, etc).

# Convert to an OpenSSL::PKey::PKey
if key.respond_to?(:to_pkey)
  openssl_pkey = key.to_pkey
end

# Access COSE key parameters
case key
when COSE::Key::OKP
  key.crv
  key.x
  key.d
when COSE::Key::EC2
  key.crv
  key.x
  key.y
  key.d
when COSE::Key::RSA
  key.n
  key.e
  key.d
  key.p
  key.q
  key.dp
  key.dq
  key.qinv
when COSE::Key::Symmetric
  key.k
end

If you already know which COSE key type is encoded in the CBOR data, then:

okp_key_cbor = "..."

cose_okp_key = COSE::Key::OKP.deserialize(okp_key_cbor)

cose_okp_key.crv
cose_okp_key.x
cose_okp_key.d
ec2_key_cbor = "..."

cose_ec2_key = COSE::Key::EC2.deserialize(ec2_key_cbor)

cose_ec2_key.crv
cose_ec2_key.x
cose_ec2_key.y
cose_ec2_key.d

# or

ec_pkey = cose_ec2_key.to_pkey # Instance of an OpenSSL::PKey::EC
symmetric_key_cbor = "..."

cose_symmetric_key = COSE::Key::Symmetric.deserialize(symmetric_key_cbor)

cose_symmetric_key.k
rsa_key_cbor = "..."

cose_rsa_key = COSE::Key::RSA.deserialize(rsa_key_cbor)

cose_rsa_key.n
cose_rsa_key.e
cose_rsa_key.d
cose_rsa_key.p
cose_rsa_key.q
cose_rsa_key.dp
cose_rsa_key.dq
cose_rsa_key.qinv

# or

rsa_pkey = cose_rsa_key.to_pkey # Instance of an OpenSSL::PKey::RSA

Serialization (from Ruby objects to CBOR)

ec_pkey = OpenSSL::PKey::EC.new("prime256v1").generate_key

cose_ec2_key_cbor = COSE::Key.serialize(ec_pkey)
rsa_pkey = OpenSSL::PKey::RSA.new(2048)

cose_rsa_key_cbor = COSE::Key.serialize(rsa_pkey)

Signing Objects

COSE_Sign

cbor_data = "..."

sign = COSE::Sign.deserialize(cbor_data)

# Verify by doing (key should be a COSE::Key):
sign.verify(key)

# or, if externally supplied authenticated data exists:
sign.verify(key, external_aad)

# Then access payload
sign.payload

COSE_Sign1

cbor_data = "..."

sign1 = COSE::Sign1.deserialize(cbor_data)

# Verify by doing (key should be a COSE::Key):
sign1.verify(key)

# or, if externally supplied authenticated data exists:
sign1.verify(key, external_aad)

# Then access payload
sign1.payload

MAC Objects

COSE_Mac

cbor_data = "..."

mac = COSE::Mac.deserialize(cbor_data)

# Verify by doing (key should be a COSE::Key::Symmetric):
mac.verify(key)

# or, if externally supplied authenticated data exists:
mac.verify(key, external_aad)

# Then access payload
mac.payload

COSE_Mac0

cbor_data = "..."

mac0 = COSE::Mac0.deserialize(cbor_data)

# Verify by doing (key should be a COSE::Key::Symmetric):
mac0.verify(key)

# or, if externally supplied authenticated data exists:
mac0.verify(key, external_aad)

# Then access payload
mac0.payload

Encryption Objects

COSE_Encrypt

cbor_data = "..."

encrypt = COSE::Encrypt.deserialize(cbor_data)

encrypt.protected_headers
encrypt.unprotected_headers
encrypt.ciphertext

encrypt.recipients.each do |recipient|
  recipient.protected_headers
  recipient.unprotected_headers
  recipient.ciphertext

  if recipient.recipients
    recipient.recipients.each do |recipient|
      recipient.protected_headers
      recipient.unprotected_headers
      recipient.ciphertext
    end
  end
end

COSE_Encrypt0

cbor_data = "..."

encrypt0 = COSE::Encrypt0.deserialize(cbor_data)

encrypt0.protected_headers
encrypt0.unprotected_headers
encrypt0.ciphertext

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/cedarcode/cose-ruby.

License

The gem is available as open source under the terms of the MIT License.

cose-ruby's People

Contributors

bdewater avatar brauliomartinezlm avatar clearlyclaire avatar grzuy avatar santiagorodriguez96 avatar waltercacau avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

cose-ruby's Issues

Handle COSE EC keys encoded without leading 0 bytes in coordinates to avoid "EC_POINT_bn2point: invalid encoding" errors

Code sample that demonstrates the issue.

encoded_key='pQECAyYgASFYHynGYDi87vkqpFOep_onzrmNjPdVBthCuIua9pvBCssiWCBZnNAreTzLOVZrLcTrh6eh-v5GrdemuIS-bVvXrk7Wdw=='
sample_key=COSE::Key.deserialize(Base64.urlsafe_decode64(encoded_key))

sample_key.to_pkey
# This fails with:
# OpenSSL::PKey::EC::Point::Error: EC_POINT_bn2point: invalid encoding
# from .../.rbenv/versions/3.3.0/lib/ruby/gems/3.3.0/gems/cose-1.3.0/lib/cose/key/ec2.rb:72:in `initialize'

puts "x.length = #{sample_key.x.length} / y.length = #{sample_key.y.length}"
# This prints:
# x.length = 31 / y.length = 32

Apparently some platforms omit leading zeros when encoding coordinates from EC keys. The example key above was generated in an iOS device by Apple's AppAttest.

Ruby-JWT gem also had to handle this issue to avoid the error.
jwt/ruby-jwt#585

I believe the fix could be relatively straightforward. Basically we need to patch this line to ensure x/y have the right length and if not add leading zeros.
https://github.com/cedarcode/cose-ruby/blob/fcde72f1351d3ba964500d91a19ab0e2d84a5878/lib/cose/key/ec2.rb#L71C27-L71C61

COSE::Key.deserialize can throw NoMemoryError

If you run COSE::Key.deserialize(SecureRandom.random_bytes(64)), then there is a fairly high chance of a NoMemoryError. I think it would be nice if a compact untrusted input always throws a recoverable error.

The following repro code crashes for me pretty reliably:

require "cose"
require 'securerandom'

errors = {}

100.times do |i|
  begin
    COSE::Key.deserialize(SecureRandom.random_bytes(64))
  rescue => ex
    errors[ex.class.name] = ex
  end
end

puts errors

Sample output:

ruby(49760,0x108de85c0) malloc: can't allocate region
*** mach_vm_map(size=597202949621485568) failed (error code=3)
ruby(49760,0x108de85c0) malloc: *** set a breakpoint in malloc_error_break to debug
ruby(49760,0x108de85c0) malloc: can't allocate region
*** mach_vm_map(size=597202949621485568) failed (error code=3)
ruby(49760,0x108de85c0) malloc: *** set a breakpoint in malloc_error_break to debug
/Users/lgarron/.data/gem/gems/cose-0.7.0/lib/cose/key.rb:24:in `decode': failed to allocate memory (NoMemoryError)
  from /Users/lgarron/.data/gem/gems/cose-0.7.0/lib/cose/key.rb:24:in `deserialize'
  from registrations.rb:8:in `block in <main>'
  from registrations.rb:6:in `times'
  from registrations.rb:6:in `<main>'

Provide a safe way to check if a key is valid.

See cedarcode/webauthn-ruby#222 and #39

To check if a COSE key is valid, it seems we have to do:

begin
  COSE::Key.deserialize(public_key_bytes)
rescue ArgumentError, EOFError, TypeError, COSE::UnknownKeyType, CBOR::UnpackError
  # ...
end

This is not quite enough, because a NoMemoryError is also possible (#39). It would be nice to have a safe way to check whether an untrusted byte string is a valid key, e.g.:

  • a method with a documented set of possible errors
  • a boolean method, e.g. COSE::Key.valid?(public_key_bytes)

create signing object with header

Hi,

I'm completely new to cbor and cose. So sorry if I might be asking super noob questions.

I'm trying to create an cbor cose signing object in ruby to hash afterwards for our system partners. They are requesting an object like this:

[
  "Signature1",
  h'a10126',
  h'',
  h'>>CBOR PAYLOAD HEX<<'
]

I understand that CBOR has headers, so the h'' values are headers and not part of the actual payload. However, I can't find the correct way of creating this object using the cose-ruby library.

Is there anyone who can support with this?

Thanks in advance.

require "cose" should require everything

$ irb
irb(main):001:0> require "cose"
=> true
irb(main):002:0> COSE
=> COSE
irb(main):003:0> COSE::Key
Traceback (most recent call last):
        4: from /.../.rubies/ruby-2.6.3/bin/irb:23:in `<main>'
        3: from /.../.rubies/ruby-2.6.3/bin/irb:23:in `load'
        2: from /.../.rubies/ruby-2.6.3/lib/ruby/gems/2.6.0/gems/irb-1.0.0/exe/irb:11:in `<top (required)>'
        1: from (irb):3
NameError (uninitialized constant COSE::Key)

Support conversion of Key object to OpenSSL-ish object

I assume most of users deserializing COSE Key objects, would need as a follow up step to operate with that key, meaning, signing, verifying a signature, encrypting or decrypting a message.

Given that, it would be very useful for the Key object to return an instance of a ready-to-operate ruby-openssl OpenSSL::PKey::PKey object.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.