Giter VIP home page Giter VIP logo

cocoafob's Introduction

Overview

CocoaFob is a set of helper code snippets for registration code generation and verification in Objective-C applications, integrated with registration code generation in Potion Store http://www.potionfactory.com/potionstore and FastSpring http://fastspring.com.

The current implementation uses DSA to generate registration keys, which significantly reduces chances of crackers producing key generators for your software. Unfortunately, it also means the registration code can be quite long and has variable length.

To make registration codes human-readable, CocoaFob encodes them using a slightly modified base32 to avoid ambiguous characters. It also groups codes in sets of five characters separated by dashes. A sample registration code produced using a 512-bit DSA key looks like this:

GAWQE-FCUGU-7Z5JE-WEVRA-PSGEQ-Y25KX-9ZJQQ-GJTQC-CUAJL-ATBR9-WV887-8KAJM-QK7DT-EZHXJ-CR99C-A

One of the advantages of DSA is that for a given registration name, each generated code is different, as there is a random element introduced during the process.

The name 'CocoaFob' is a combination of 'Cocoa' (the Mac and iOS programming framework) and 'Fob' (a key fob is something you keep your keys on).

Features

CocoaFob provides the following for your application:

  • Secure asymmetric cryptography-based registration key generation and verification using DSA.

  • Support for key generation in Objective-C and Ruby and verification in Objective-C for integration in both your Cocoa application and Potion Store.

  • Support for custom URL scheme for automatic application registration.

There is no framework or a library to link against. You include the files you need in your application project directly and are free to modify the code in any way you need.

You may also find other snippets of code useful, such as base32 and base64 encoding/decoding functions, as well as categories extending NSString and NSData classes with base32 and base64 methods.

Usage

The best way to get the latest version of the code is to clone the main Git repository:

git://github.com/glebd/cocoafob.git

You can also download the latest version from the CocoaFob home page at http://github.com/glebd/cocoafob/.

For more complete examples of how to use CocoaFob, look at the following projects by Alex Clarke: CodexFab https://github.com/machinecodex/CodexFab/ and LicenseExample https://github.com/machinecodex/CodexFab_LicenseExample/.

Providing a Registration Source String

To register an application that uses CocoaFob, it is necessary to provide a string of source information, which may be as simple as a registration name or arbitrarily complex in case your application is processing the included information in a user-friendly way. For example, as suggested in the sample implementation of Potion Store licence generator, a source string may contain application name, user name and number of copies:

myapp|Joe Bloggs|1

When sending registration mail, you need to provide both the source string and the registration code. Potion Store does this for you. However, small modifications are needed to make automatic activation work.

Generating automatic activation URLs

Potion Store supports automatic activation of an installed application by clicking on a special link in a registration email or on the Thank You store page. For this to work, you need to:

  • make your application support a registration URL scheme;

  • modify Potion Store so that automatic activation link contains not only registration code, but registration source string as well.

The stock implementation of Potion Store registration code support assumes a registration code is all that is needed to register an application. However, CocoaFob needs to know both registration name and registration code in order to verify the licence. This means when Potion Store generates an automatic registration URL for your application, it needs to include registration source string in it. One of the possible solutions is as follows:

  • In your database migration 001_create_tables.rb, increase the length of license_key column in line_items table to 128 characters:
    t.column "license_key", :string, :limit => 128
  • In the file app/models/line_item.rb, add the following line at the top:
    require "base64"`
  • In the same file find function called license_url near the bottom of the file. Replace it with the following (or modify to your heart's content):
  def license_url
    licensee_name_b64 = Base64.encode64(self.order.licensee_name)
    return "#{self.product.license_url_scheme}://#{licensee_name_b64}/#{self.license_key}" rescue nil
  end

This will make generated registration codes to contain base64-encoded licensee name. When your application is opened by clicking on the registration link, it will parse the code, extract the registration name and use it to verify the licence.

Supporting registration URL schema in your app

The following files in objc directory provide a sample implementation of support for custom URL schema for application registration. The code is almost literally taken from [3].

To support registration URLs in your application:

  • Add files MyApp.scriptSuite and MyApp.scriptTerminology to your project's resources, adjusting strings inside appropriately.

  • Add the following to your application's Info.plist file under /plist/dict key (replace mycompany and myapp with strings appropriate for your company and application):

  <key>NSAppleScriptEnabled</key>
  <string>YES</string>
  <key>CFBundleURLTypes</key>
  <array>
      <dict>
          <key>CFBundleURLSchemes</key>
          <array>
              <string>com.mycompany.myapp.lic</string>
          </array>
      </dict>
  </array>
  • Add the files URLCommand.h and URLCommand.m to your project, paying attention to the TODO: comments in them. Specifically, you may want to save registration information to your application's preferences, and also broadcast a notification of a changed registration information after verifying the supplied registration URL.

  • Be sure the URL scheme name in the Info.plist file (com.mycompany.myapp.lic) is the same as the one in the database generation script for Potion Store. It is the file db/migrate/001_create_tables.rb, and the variable is called license_url_scheme.

Test the URL schema support by making a test purchase which results in displaying an activation link, and clicking on it. If you are running your application in debugger, place a breakpoint in the instance method performWithURL: of the class URLCommand. The breakpoint will be triggered when you click on the registration link. You can extract the link into a standalone HTML file so that is available for testing without making any additional test purchases.

Generating Keys

IMPORTANT NOTE: Included keys are for demonstration and testing purposes only. DO NOT USE THE INCLUDED KEYS IN YOUR SOFTWARE. Before incorporating CocoaFob into your application, you need to generate a pair of your own DSA keys. I used key length of 512 bit which I thought was enough for the registration code generation purposes.

(0) Make sure OpenSSL is installed. (If you're using Mac OS X, it already is.)

(1) Generate DSA parameters:

openssl dsaparam -out dsaparam.pem 512

(2) Generate an unencrypted DSA private key:

openssl gendsa -out privkey.pem dsaparam.pem

(3) Extract public key from private key:

openssl dsa -in privkey.pem -pubout -out pubkey.pem

See [2] for more information.

Licence

CocoaFob is distributed under the BSD License http://www.opensource.org/licenses/bsd-license.php. See the LICENSE file.

Credits

[0] The Mac developer community that continues to amaze me.

[1] Base32 implementation is Copyright © 2007 by Samuel Tesla and comes from Ruby base32 gem: http://rubyforge.org/projects/base32/.

[2] OpenSSL key generation HOWTO: http://www.openssl.org/docs/HOWTO/keys.txt

[3] Handling URL schemes in Cocoa: a blog post by Kimbro Staken

[4] Registering a protocol handler for an App: a post on CocoaBuilder mailing list

[5] PHP implementation courtesy of Sandro Noel

[6] Security framework-based implementation by Matt Stevens, http://codeworkshop.net

[7] New API by Danny Greg, http://dannygreg.com

cocoafob's People

Contributors

0xced avatar billymeltdown avatar darwin avatar dependabot[bot] avatar divinedominion avatar douglashill avatar fheidenreich avatar gblazex avatar glebd avatar karlvr avatar ksuther avatar mrmage avatar multicolourpixel avatar r0uter avatar sdegutis avatar sweetppro avatar

Stargazers

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

Watchers

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

cocoafob's Issues

Memory Leak in CFobLicVerifier?

I think there may be a memory leak in CFobLicVerifier when compiled with ARC (I'm running Xcode 7.2.1/ OS X 10.11.3).

@property (retain) __attribute__((NSObject)) SecKeyRef publicKey;

If I take that out, set the publicKey ivar directly and retain it (and release it when I'm done) that seemed to get rid of the leak.

Reduce cracking

Hello,

I am using your code for licensing my app. Unfortunately it has been cracked teh day of the release. Do you have any tip to make it a little more secure?

Thanks and regards,

Export for Localization Error

We develop an app in objective c using Xcode 7.3.

When attempting to export .xliff's using Xcode's built in "Export for Localization" we received this error:
localization_error

5/5/16 2:11:40.719 PM Xcode[23346]: [MT] DVTAssertions: Warning in /Library/Caches/com.apple.xbs/Sources/IDEFrameworks/IDEFrameworks-10183.3/IDEFoundation/Localization/IDELocalizationWork.m:355 Details: Failed to read strings file "/var/folders/tn/5fw34l7s7f944602lkyhry_w0000gn/T/Xcode3SourceStringsAdaptor-D43C45A7-9F42-439D-BF39-D4CBA29EC0C3/Localizable.strings", underlying error: The data couldn’t be read because it isn’t in the correct format. Object: <Xcode3LocalizedSourceStringsAdaptorTableWorkContext: 0x7f933867e860> Method: -work Thread: <NSThread: 0x7f9382517c60>{number = 1, name = main} Please file a bug at http://bugreport.apple.com with this warning message and any useful information you can provide.

After further investigation we believe it's related to this macro in CFobError.m:

NSLocalizedStringFromTableInBundle(description, nil, [NSBundle bundleForClass:[CFobLicVerifier class]], nil)

Changing it to this line appears to fix the issue:

[[NSBundle bundleForClass:[CFobLicVerifier class]] localizedStringForKey:description value:@"" table:nil]

Should we be filing a radar or is this something we should adjust in cocoafob?

CommonCrypto

Is there any chance to use CommonCrypto instead of OpenSSL? I'd really like to get rid of all those deprecation warnings.

Link to simple docs?

Hey there,

Is there a page (wiki, external documentation, etc) that has a somewhat simple step-by-step guide to using CocoaFob? I am having a lot of trouble getting it up and running, and was hoping for something along the lines of what Sparkle provides.

If this documentation exists, where might I find it? If not, I may end up writing something like that, it might be helpful for others too :)

Build fails with no issues using ARC

My builds were failing while reporting 'no issues' when compiling in an ARC-enabled project (regardless of the use of the -fno-objc-arc flag for cocoafob-related class files). After a bit of digging, it appears that CFobLicGenerator's generateRegCodeForName:error: method is to blame. It returns an NSString, but attempts to return a boolean under two conditions. It's a fairly quick change to have it return nil instead.

Here's the detailed build log. Hopefully it helps:

/CocoaFob/CFobLicGenerator.m:115:10: error: implicit conversion of 'BOOL' (aka 'signed char') to 'NSString *' is disallowed with ARC
                return NO;
                       ^~
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.7.sdk/usr/include/objc/objc.h:51:25: note: expanded from macro 'NO'
#define NO              (BOOL)0
                        ^~~~~~~
/CocoaFob/CFobLicGenerator.m:123:10: error: implicit conversion of 'BOOL' (aka 'signed char') to 'NSString *' is disallowed with ARC
                return NO;
                       ^~

Swift: Problem with extra characters on the registration key

While playing around, I noticed that adding extra characters to the end of the registration key still produces a valid return in the swift5 implementation. This is down to how the Security framework by apple handles additional characters during a Base32 decode: They simply get ignored and no error is thrown!

Example: The swift implementation will accept both of these registration keys:

  • GAWQE-F9AQP-XJCCL-PAFAX-NU5XX-EUG6W-KLT3H-VTEB9-A9KHJ-8DZ5R-DL74G-TU4BN-7ATPY-3N4XB-V4V27-Q
  • GAWQE-F9AQP-XJCCL-PAFAX-NU5XX-EUG6W-KLT3H-VTEB9-A9KHJ-8DZ5R-DL74G-TU4BN-7ATPY-3N4XB-V4V27-Qasdf
  • asdfGAWQE-F9AQP-XJCCL-PAFAX-NU5XX-EUG6W-KLT3H-VTEB9-A9KHJ-8DZ5R-DL74G-TU4BN-7ATPY-3N4XB-V4V27-Q

You can reproduce this by adding the following test to the swift5 project in Xcode:

    func testVerifyAdditionalCharactersFail() {
      let verifier = LicenseVerifier(publicKeyPEM: publicKeyPEM)
      XCTAssertNotNil(verifier?.pubKey)
      let name = "Joe Bloggs"
      let regKey = "GAWQE-F9AQP-XJCCL-PAFAX-NU5XX-EUG6W-KLT3H-VTEB9-A9KHJ-8DZ5R-DL74G-TU4BN-7ATPY-3N4XB-V4V27-Qasdf"
      let result = verifier?.verify(regKey, forName: name) ?? false
      XCTAssertFalse(result)
    }

The expected result would be that this is an invalid key, thus asserting the result with a false value. However, this test will fail, because the verification function will return a true!

I also tried this in the Python implementation and that "successfully" failed during the Base32 decode -> All okay.

As I don't know the security framework to well, I added the following code to the LicenceVerifier.swift:

      ...
      let decoder = try getDecoder(keyData)
      let signature = try cfTry(.error) { SecTransformExecute(decoder, $0) }
      
      // reverse the signature to check for truncated data / additional data entered by the user
      let encoder = try getEncoder(signature as! Data)
      let reverseSignature = try cfTry(.error) { SecTransformExecute(encoder, $0) }
      let reverseSignatureString = String(decoding: reverseSignature as! Data, as: UTF8.self).replacingOccurrences(of: "=", with: "")
      if(reverseSignatureString != keyString) { return false }
      
      let verifier = try getVerifier(self.pubKey, signature: signature as! Data, nameData: nameData)
      let result = try cfTry(.error) { SecTransformExecute(verifier, $0) }
      ...

and a bit further down add this function:

  // MARK: - Helper functions
  fileprivate func getEncoder(_ signature: Data) throws -> SecTransform {
    let encoder = try cfTry(.error) { return SecEncodeTransformCreate(kSecBase32Encoding, $0) }
    let _ = try cfTry(.error) { return SecTransformSetAttribute(encoder, kSecTransformInputAttributeName, signature as CFTypeRef, $0) }
    return encoder
  }

I don't think this is the nicest solution, but it works. Does anyone else know this might be fixed with a cleaner method? Seems like a workaround for something that I have missed!

CocoaFob and Snow Leopard

Do you know if there is an alternate way to implement the CFobLicVerifier that is compatible with Snow Leopard? My application is crashing on startup there. It was initially a problem with base32 encoding, with this error shown in the log:
dyld: Symbol not found: _kSecBase32Encoding
I found a workaround to that problem by finding code that decided base32 using different APIs. Now I'm having the same kind of error with _kSecDigestSHA1. I haven't yet found alternate APIs for this step that are Snow Leopard compatible. Do you know of any?

Class URLCommand doesn't launch my app when my custom URL is clicked

I presume it's supposed to, with the AppleScript files in the bundle and all.

I think this isn't really a code bug, just a lack of documentation on all the steps required to get it to work. My app certainly does notice a clicked URL that it's registered for when it's already open, it just doesn't get launched when it's closed.

Migrating from openssl

Since Apple is going to deprecate openssl are there any plans on migrating to Common Crypto framework?

Thanks

License specification

I want to make a CocoaPod from the Swift 3 version. But a license is required for that. I noticed there's nothing but the Copyright notice included in this repo.

What do you think about including the MIT license?

False positive on master branch

Hi,

I'm testing CocoaFob master branch (can't use no-openssl branch as I need to target 10.6) and have come across a false positive situation in objective-c.

I generated the licence code using the PHP script with the following input:

ProductCode: MyAppAB
Name: mark
email: [email protected]

Which produced the following licence code: GAWQE-F9A2F-TS2DW-ZYSZE-ZSK2N-PL23V-H76X8-G7NVX-A9KB3-8NFYW-L8WFD-3CD72-EYGHM-ZYKLG-BC8ZQ-Q

That, correctly, verifies in PHP and Objective-C. However, changing the final character (from Q to R for example) also verifies in Objective-C, but not PHP. PHP correctly says it's invalid and gives an error about "found non-zero padding in Base32Decode".

The same is true of licence code GAWQE-FBMG4-RB8NU-4642P-T4FZF-5224K-DGSXZ-M7FQC-CUALV-WDN7C-9X8KW-FQG5B-5TQTZ-B8NPR-5D5Y5-Q which was generated from the same input.

SecTransform is deprecated in macOS 12

I don't think there are any other macOS APIs that currently support DSA. Time to bring back OpenSSL or is there a smaller third-party library that does DSA?

framework not found CocoaFob

Weirdly, when I try to use CocoaFob - whether in an App I'm writing myself, or building the cocoafob example in this repository, it always fails with:

ld: framework not found CocoaFob
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I can build the frameworks - no issues there - but when I try to use them it all goes wrong! Xcode 8.2.1

Add Swift Package for CocoaFob

Once #53 is fixed by adding OpenSSL back, we could look into shipping a Swift Package. It's easy with the current code, but I'd rather wait for #53 -- then we don't have to worry about fixing the SwiftPM build process and wrapping libopenssl.a during the fix.

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.