packages feed

credential-store (empty) → 0.1.0.0

raw patch · 10 files changed

+729/−0 lines, 10 filesdep +Win32dep +basedep +bytestringsetup-changed

Dependencies added: Win32, base, bytestring, containers, credential-store, cryptonite, dbus, memory, safe-exceptions, tasty, tasty-hunit

Files

+ LICENSE view
@@ -0,0 +1,201 @@+                                 Apache License+                           Version 2.0, January 2004+                        http://www.apache.org/licenses/++   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++   1. Definitions.++      "License" shall mean the terms and conditions for use, reproduction,+      and distribution as defined by Sections 1 through 9 of this document.++      "Licensor" shall mean the copyright owner or entity authorized by+      the copyright owner that is granting the License.++      "Legal Entity" shall mean the union of the acting entity and all+      other entities that control, are controlled by, or are under common+      control with that entity. For the purposes of this definition,+      "control" means (i) the power, direct or indirect, to cause the+      direction or management of such entity, whether by contract or+      otherwise, or (ii) ownership of fifty percent (50%) or more of the+      outstanding shares, or (iii) beneficial ownership of such entity.++      "You" (or "Your") shall mean an individual or Legal Entity+      exercising permissions granted by this License.++      "Source" form shall mean the preferred form for making modifications,+      including but not limited to software source code, documentation+      source, and configuration files.++      "Object" form shall mean any form resulting from mechanical+      transformation or translation of a Source form, including but+      not limited to compiled object code, generated documentation,+      and conversions to other media types.++      "Work" shall mean the work of authorship, whether in Source or+      Object form, made available under the License, as indicated by a+      copyright notice that is included in or attached to the work+      (an example is provided in the Appendix below).++      "Derivative Works" shall mean any work, whether in Source or Object+      form, that is based on (or derived from) the Work and for which the+      editorial revisions, annotations, elaborations, or other modifications+      represent, as a whole, an original work of authorship. For the purposes+      of this License, Derivative Works shall not include works that remain+      separable from, or merely link (or bind by name) to the interfaces of,+      the Work and Derivative Works thereof.++      "Contribution" shall mean any work of authorship, including+      the original version of the Work and any modifications or additions+      to that Work or Derivative Works thereof, that is intentionally+      submitted to Licensor for inclusion in the Work by the copyright owner+      or by an individual or Legal Entity authorized to submit on behalf of+      the copyright owner. For the purposes of this definition, "submitted"+      means any form of electronic, verbal, or written communication sent+      to the Licensor or its representatives, including but not limited to+      communication on electronic mailing lists, source code control systems,+      and issue tracking systems that are managed by, or on behalf of, the+      Licensor for the purpose of discussing and improving the Work, but+      excluding communication that is conspicuously marked or otherwise+      designated in writing by the copyright owner as "Not a Contribution."++      "Contributor" shall mean Licensor and any individual or Legal Entity+      on behalf of whom a Contribution has been received by Licensor and+      subsequently incorporated within the Work.++   2. Grant of Copyright License. Subject to the terms and conditions of+      this License, each Contributor hereby grants to You a perpetual,+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable+      copyright license to reproduce, prepare Derivative Works of,+      publicly display, publicly perform, sublicense, and distribute the+      Work and such Derivative Works in Source or Object form.++   3. Grant of Patent License. Subject to the terms and conditions of+      this License, each Contributor hereby grants to You a perpetual,+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable+      (except as stated in this section) patent license to make, have made,+      use, offer to sell, sell, import, and otherwise transfer the Work,+      where such license applies only to those patent claims licensable+      by such Contributor that are necessarily infringed by their+      Contribution(s) alone or by combination of their Contribution(s)+      with the Work to which such Contribution(s) was submitted. If You+      institute patent litigation against any entity (including a+      cross-claim or counterclaim in a lawsuit) alleging that the Work+      or a Contribution incorporated within the Work constitutes direct+      or contributory patent infringement, then any patent licenses+      granted to You under this License for that Work shall terminate+      as of the date such litigation is filed.++   4. Redistribution. You may reproduce and distribute copies of the+      Work or Derivative Works thereof in any medium, with or without+      modifications, and in Source or Object form, provided that You+      meet the following conditions:++      (a) You must give any other recipients of the Work or+          Derivative Works a copy of this License; and++      (b) You must cause any modified files to carry prominent notices+          stating that You changed the files; and++      (c) You must retain, in the Source form of any Derivative Works+          that You distribute, all copyright, patent, trademark, and+          attribution notices from the Source form of the Work,+          excluding those notices that do not pertain to any part of+          the Derivative Works; and++      (d) If the Work includes a "NOTICE" text file as part of its+          distribution, then any Derivative Works that You distribute must+          include a readable copy of the attribution notices contained+          within such NOTICE file, excluding those notices that do not+          pertain to any part of the Derivative Works, in at least one+          of the following places: within a NOTICE text file distributed+          as part of the Derivative Works; within the Source form or+          documentation, if provided along with the Derivative Works; or,+          within a display generated by the Derivative Works, if and+          wherever such third-party notices normally appear. The contents+          of the NOTICE file are for informational purposes only and+          do not modify the License. You may add Your own attribution+          notices within Derivative Works that You distribute, alongside+          or as an addendum to the NOTICE text from the Work, provided+          that such additional attribution notices cannot be construed+          as modifying the License.++      You may add Your own copyright statement to Your modifications and+      may provide additional or different license terms and conditions+      for use, reproduction, or distribution of Your modifications, or+      for any such Derivative Works as a whole, provided Your use,+      reproduction, and distribution of the Work otherwise complies with+      the conditions stated in this License.++   5. Submission of Contributions. Unless You explicitly state otherwise,+      any Contribution intentionally submitted for inclusion in the Work+      by You to the Licensor shall be under the terms and conditions of+      this License, without any additional terms or conditions.+      Notwithstanding the above, nothing herein shall supersede or modify+      the terms of any separate license agreement you may have executed+      with Licensor regarding such Contributions.++   6. Trademarks. This License does not grant permission to use the trade+      names, trademarks, service marks, or product names of the Licensor,+      except as required for reasonable and customary use in describing the+      origin of the Work and reproducing the content of the NOTICE file.++   7. Disclaimer of Warranty. Unless required by applicable law or+      agreed to in writing, Licensor provides the Work (and each+      Contributor provides its Contributions) on an "AS IS" BASIS,+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+      implied, including, without limitation, any warranties or conditions+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+      PARTICULAR PURPOSE. You are solely responsible for determining the+      appropriateness of using or redistributing the Work and assume any+      risks associated with Your exercise of permissions under this License.++   8. Limitation of Liability. In no event and under no legal theory,+      whether in tort (including negligence), contract, or otherwise,+      unless required by applicable law (such as deliberate and grossly+      negligent acts) or agreed to in writing, shall any Contributor be+      liable to You for damages, including any direct, indirect, special,+      incidental, or consequential damages of any character arising as a+      result of this License or out of the use or inability to use the+      Work (including but not limited to damages for loss of goodwill,+      work stoppage, computer failure or malfunction, or any and all+      other commercial damages or losses), even if such Contributor+      has been advised of the possibility of such damages.++   9. Accepting Warranty or Additional Liability. While redistributing+      the Work or Derivative Works thereof, You may choose to offer,+      and charge a fee for, acceptance of support, warranty, indemnity,+      or other liability obligations and/or rights consistent with this+      License. However, in accepting such obligations, You may act only+      on Your own behalf and on Your sole responsibility, not on behalf+      of any other Contributor, and only if You agree to indemnify,+      defend, and hold each Contributor harmless for any liability+      incurred by, or claims asserted against, such Contributor by reason+      of your accepting any such warranty or additional liability.++   END OF TERMS AND CONDITIONS++   APPENDIX: How to apply the Apache License to your work.++      To apply the Apache License to your work, attach the following+      boilerplate notice, with the fields enclosed by brackets "{}"+      replaced with your own identifying information. (Don't include+      the brackets!)  The text should be enclosed in the appropriate+      comment syntax for the file format. We also recommend that a+      file or class name and description of purpose be included on the+      same "printed page" as the copyright notice for easier+      identification within third-party archives.++   Copyright {yyyy} {name of copyright owner}++   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++       http://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.
+ README.md view
@@ -0,0 +1,2 @@+# credential-store+Windows and Linux credentials storage
+ Setup.hs view
@@ -0,0 +1,2 @@+import Distribution.Simple+main = defaultMain
+ app/Main.hs view
@@ -0,0 +1,15 @@+module Main where++import qualified Data.ByteString.Char8 as BS8++import System.CredentialStore++main :: IO ()+main =+    withCredentialStore $ \store -> do+        putCredential store "foo" (BS8.pack "burr")+        v <- getCredential store "foo"+        print (v :: Maybe BS8.ByteString)+        deleteCredential store "foo"+        v' <- getCredential store "foo"+        print (v' :: Maybe BS8.ByteString)
+ credential-store.cabal view
@@ -0,0 +1,62 @@+name:                credential-store+version:             0.1.0.0+synopsis:            Library to access secure credential storage providers+description:+  Cross-platform library for storing secrets.+  .+  Uses Windows credential store, gnome-keyring or kwallet as backends.+homepage:            https://github.com/rblaze/credential-store#readme+license:             Apache-2.0+license-file:        LICENSE+author:              Andrey Sverdlichenko+maintainer:          blaze@ruddy.ru+copyright:           2017 Andrey Sverdlichenko+category:            Desktop+build-type:          Simple+extra-source-files:  README.md+cabal-version:       >=1.10++library+  hs-source-dirs:      src+  exposed-modules:     System.CredentialStore+  build-depends:       base >= 4.7 && < 5+                     , bytestring+                     , containers+                     , cryptonite+                     , memory+                     , safe-exceptions+  if os(windows)+    cpp-options:       -DWINBUILD+    build-depends:     Win32+    other-modules:     System.CredentialStore.WinTypes+                       System.CredentialStore.Windows+  else+    build-depends:     dbus+    other-modules:     System.CredentialStore.DBusSecretService+  default-language:    Haskell2010+  ghc-options:         -W -Wall++executable credential-store-exe+  hs-source-dirs:      app+  main-is:             Main.hs+  ghc-options:         -threaded -rtsopts -with-rtsopts=-N -W -Wall+  build-depends:       base+                     , bytestring+                     , credential-store+  default-language:    Haskell2010++test-suite credential-store-test+  type:                exitcode-stdio-1.0+  hs-source-dirs:      test+  main-is:             Spec.hs+  build-depends:       base+                     , bytestring+                     , credential-store+                     , tasty+                     , tasty-hunit+  ghc-options:         -threaded -rtsopts -with-rtsopts=-N -W -Wall+  default-language:    Haskell2010++source-repository head+  type:     git+  location: https://github.com/rblaze/credential-store
+ src/System/CredentialStore.hs view
@@ -0,0 +1,10 @@+{-# Language CPP #-}+module System.CredentialStore+    ( module X+    ) where++#ifdef WINBUILD+import System.CredentialStore.Windows as X+#else+import System.CredentialStore.DBusSecretService as X+#endif
+ src/System/CredentialStore/DBusSecretService.hs view
@@ -0,0 +1,215 @@+{-# Language PatternGuards, RecordWildCards, ScopedTypeVariables #-}+module System.CredentialStore.DBusSecretService+    ( CredentialStore+    , getCredential+    , putCredential+    , deleteCredential+    , withCredentialStore+    ) where++import Control.Exception.Safe+import Control.Monad+import Crypto.Cipher.AES+import Crypto.Cipher.Types+import Crypto.Data.Padding+import Crypto.Error+import Crypto.Hash+import Crypto.KDF.HKDF+import Crypto.PubKey.DH+import Crypto.Random+import DBus+import DBus.Client+import Data.Bits+import Data.ByteArray+import qualified Data.ByteString as BS+import qualified Data.Map.Strict as M++-- |Abstract context for credential store communications+data CredentialStore = CredentialStore+    { csClient :: Client+    , csSession :: ObjectPath+    , csCipher :: AES128+    }++type CredentialObject = (ObjectPath, BS.ByteString, BS.ByteString, String)++noObject :: ObjectPath+noObject = objectPath_ "/"++destination :: BusName+destination = busName_ "org.freedesktop.secrets"++servicePath :: ObjectPath+servicePath = objectPath_ "/org/freedesktop/secrets"++serviceInterface :: InterfaceName+serviceInterface = interfaceName_ "org.freedesktop.Secret.Service"++openSession :: MemberName+openSession = memberName_ "OpenSession"++unlock :: MemberName+unlock = memberName_ "Unlock"++defaultCollection :: ObjectPath+defaultCollection = objectPath_ "/org/freedesktop/secrets/aliases/default"++collectionInterface :: InterfaceName+collectionInterface = interfaceName_ "org.freedesktop.Secret.Collection"++createItem :: MemberName+createItem = memberName_ "CreateItem"++searchItems :: MemberName+searchItems = memberName_ "SearchItems"++itemInterface :: InterfaceName+itemInterface = interfaceName_ "org.freedesktop.Secret.Item"++getSecret :: MemberName+getSecret = memberName_ "GetSecret"++delete :: MemberName+delete = memberName_ "Delete"++serviceCall :: ObjectPath -> InterfaceName -> MemberName -> MethodCall+serviceCall o i m = (methodCall o i m) { methodCallDestination = Just destination }++dhPrime :: Integer+dhPrime = 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF++dhParams :: Params+dhParams = Params+    { params_p = dhPrime+    , params_g = 2+    , params_bits = 1024+    }++-- |Open credential store and execute function passing it as parameter.+-- Store is closed even in presence of exceptions+withCredentialStore :: (CredentialStore -> IO a) -> IO a+withCredentialStore = bracket openStore closeStore+    where+    openStore = do+        privateKey <- generatePrivate dhParams+        let publicKey = calculatePublic dhParams privateKey+        bracketOnError connectSession disconnect $ \client -> do+            reply <- call_ client $+                (serviceCall servicePath serviceInterface openSession)+                { methodCallBody = [ toVariant "dh-ietf1024-sha256-aes128-cbc-pkcs7", toVariant $ toVariant $ dumpKey publicKey ]+                , methodCallAutoStart = True+                }+            case methodReturnBody reply of+                [serverKeyVar, objectPathVar]+                    | Just v <- fromVariant objectPathVar+                    , Just skv <- fromVariant serverKeyVar+                    , Just keyDump <- fromVariant skv -> do+                    let serverKey = readKey keyDump+                    let SharedKey shared = getShared dhParams privateKey serverKey+                    let salt = BS.replicate (hashDigestSize (undefined :: SHA256)) 0+                    let prk = extract salt shared+                    let sessionKey = expand (prk :: PRK SHA256) BS.empty (128 `div` 8)+                    cipher <- throwCryptoErrorIO $ cipherInit (sessionKey :: ScrubbedBytes)+                    return CredentialStore+                        { csClient = client+                        , csSession = v+                        , csCipher = cipher+                        }+                body -> throw $ clientError $ "invalid OpenSession response" ++ show body++    closeStore = disconnect . csClient++-- |Read named credential from store+getCredential :: ByteArray ba => CredentialStore -> String -> IO (Maybe ba)+getCredential store@CredentialStore{..} name = do+    items <- findCredentials store name+    unlockReply <- call_ csClient $+        (serviceCall servicePath serviceInterface unlock)+            { methodCallBody = [ toVariant items ] }+    unlocked <- case methodReturnBody unlockReply of+        [ unlocked, _ ] | Just objs <- fromVariant unlocked -> return objs+        body -> throw $ clientError $ "invalid Unlock response" ++ show body+    case unlocked of+        [] -> return Nothing+        (objpath : _) -> do+            getReply <- call_ csClient $+                (serviceCall objpath itemInterface getSecret)+                    { methodCallBody = [ toVariant csSession ] }+            case methodReturnBody getReply of+                [ obj ] | Just co <- fromVariant obj ->+                    fmap Just $ decryptCredential csCipher (credParam co) (credData co)+                body -> throw $ clientError $ "invalid GetSecret response" ++ show body+  where+    credData :: CredentialObject -> BS.ByteString+    credData (_, _, v, _) = v+    credParam (_, p, _, _) = p++-- |Write named credential to store, overwriting existing one+putCredential :: ByteArray ba => CredentialStore -> String -> ba -> IO ()+putCredential CredentialStore{..} name value = do+    (cred, iv) <- encryptCredential csCipher value+    reply <- call_ csClient $+        (serviceCall defaultCollection collectionInterface createItem)+        { methodCallBody =+            [ toVariant $ M.fromList+                [ ("org.freedesktop.Secret.Item.Label", toVariant name)+                , ("org.freedesktop.Secret.Item.Attributes",+                    toVariant $ M.singleton "credentialName" name)+                ]+            , toVariant+                ( csSession+                , iv+                , cred+                , "text/plain; charset=utf8" -- XXX who knows, really+                )+            , toVariant True+            ]+        }+    case methodReturnBody reply of+        [ path, _ ] | Just p <- fromVariant path -> when (p == noObject) $ throw (clientError "prompt required")+        body -> throw $ clientError $ "invalid CreateItem response" ++ show body++-- |Delete named credential from store+deleteCredential :: CredentialStore -> String -> IO ()+deleteCredential store@CredentialStore{..} name = do+    items <- findCredentials store name+    forM_ items $ \objpath ->+        call_ csClient $ serviceCall objpath itemInterface delete++findCredentials :: CredentialStore -> String -> IO [ObjectPath]+findCredentials CredentialStore{..} name = do+    searchReply <- call_ csClient $+        (serviceCall defaultCollection collectionInterface searchItems)+            { methodCallBody = [ toVariant $ M.singleton "credentialName" name ] }+    case methodReturnBody searchReply of+        [ v ] | Just items <- fromVariant v -> return items+        body -> throw $ clientError $ "invalid SearchItems response" ++ show body++decryptCredential :: (BlockCipher c, ByteArray ba) => c -> BS.ByteString -> BS.ByteString -> IO ba+decryptCredential cipher ivbytes bs = do+    iv <- case makeIV ivbytes of+        Just iv -> return iv+        Nothing -> throw $ clientError $ "invalid credential IV"+    let decrypted = cbcDecrypt cipher iv $ convert bs+    case unpad (PKCS7 $ blockSize cipher) decrypted of+        Nothing -> throw $ clientError $ "invalid decrypred credential"+        Just cred -> return cred++encryptCredential :: (BlockCipher c, ByteArray ba) => c -> ba -> IO (BS.ByteString, BS.ByteString)+encryptCredential cipher ba = do+    let padded = pad (PKCS7 $ blockSize cipher) ba+    ivbytes <- getRandomBytes (blockSize cipher)+    let Just iv = makeIV ivbytes+    let encrypted = cbcEncrypt cipher iv padded+    return (convert encrypted, ivbytes)++dumpKey :: PublicNumber -> BS.ByteString+dumpKey (PublicNumber key) = BS.reverse $ BS.unfoldr step key+  where+    step 0 = Nothing+    step i = Just (fromIntegral i, i `shiftR` 8)++readKey :: BS.ByteString -> PublicNumber+readKey = PublicNumber . BS.foldl' step 0+  where+    step i b = i `shiftL` 8 .|. fromIntegral b
+ src/System/CredentialStore/WinTypes.hsc view
@@ -0,0 +1,105 @@+module System.CredentialStore.WinTypes where++#include <windows.h>+#include <wincred.h>++import Foreign.Ptr+import Foreign.Storable+import System.Win32.Time+import System.Win32.Types++data CREDENTIAL_ATTRIBUTE = CREDENTIAL_ATTRIBUTE+    { caKeyword     :: LPTSTR+    , caFlags       :: DWORD+    , caValueSize   :: DWORD+    , caValue       :: LPBYTE+    }+    deriving Show++instance Storable CREDENTIAL_ATTRIBUTE where+    sizeOf _ = #size CREDENTIAL_ATTRIBUTE+    alignment _ = #alignment CREDENTIAL_ATTRIBUTE+    poke buf st = do+        (#poke CREDENTIAL_ATTRIBUTE, Keyword)   buf (caKeyword st)+        (#poke CREDENTIAL_ATTRIBUTE, Flags)     buf (caFlags st)+        (#poke CREDENTIAL_ATTRIBUTE, ValueSize) buf (caValueSize st)+        (#poke CREDENTIAL_ATTRIBUTE, Value)     buf (caValue st)+    peek buf = do+        keyword     <- (#peek CREDENTIAL_ATTRIBUTE, Keyword) buf+        flags       <- (#peek CREDENTIAL_ATTRIBUTE, Flags) buf+        valueSize   <- (#peek CREDENTIAL_ATTRIBUTE, ValueSize) buf+        value       <- (#peek CREDENTIAL_ATTRIBUTE, Value) buf+        return $ CREDENTIAL_ATTRIBUTE keyword flags valueSize value++data CREDENTIAL = CREDENTIAL+    { crFlags               :: DWORD+    , crType                :: DWORD+    , crTargetName          :: LPTSTR+    , crComment             :: LPTSTR+    , crLastWritten         :: FILETIME+    , crCredentialBlobSize  :: DWORD+    , crCredentialBlob      :: LPBYTE+    , crPersist             :: DWORD+    , crAttributeCount      :: DWORD+    , crAttributes          :: Ptr CREDENTIAL_ATTRIBUTE+    , crTargetAlias         :: LPTSTR+    , crUserName            :: LPTSTR+    }+    deriving Show++instance Storable CREDENTIAL where+    sizeOf _ = #size CREDENTIAL+    alignment _ = #alignment CREDENTIAL+    poke buf st = do+        (#poke CREDENTIAL, Flags)              buf (crFlags st)+        (#poke CREDENTIAL, Type)               buf (crType st)+        (#poke CREDENTIAL, TargetName)         buf (crTargetName st)+        (#poke CREDENTIAL, Comment)            buf (crComment st)+        (#poke CREDENTIAL, LastWritten)        buf (crLastWritten st)+        (#poke CREDENTIAL, CredentialBlobSize) buf (crCredentialBlobSize st)+        (#poke CREDENTIAL, CredentialBlob)     buf (crCredentialBlob st)+        (#poke CREDENTIAL, Persist)            buf (crPersist st)+        (#poke CREDENTIAL, AttributeCount)     buf (crAttributeCount st)+        (#poke CREDENTIAL, Attributes)         buf (crAttributes st)+        (#poke CREDENTIAL, TargetAlias)        buf (crTargetAlias st)+        (#poke CREDENTIAL, UserName)           buf (crUserName st)+    peek buf = do+        flags              <- (#peek CREDENTIAL, Flags) buf+        type'              <- (#peek CREDENTIAL, Type) buf+        targetName         <- (#peek CREDENTIAL, TargetName) buf+        comment            <- (#peek CREDENTIAL, Comment) buf+        lastWritten        <- (#peek CREDENTIAL, LastWritten) buf+        credentialBlobSize <- (#peek CREDENTIAL, CredentialBlobSize) buf+        credentialBlob     <- (#peek CREDENTIAL, CredentialBlob) buf+        persist            <- (#peek CREDENTIAL, Persist) buf+        attributeCount     <- (#peek CREDENTIAL, AttributeCount) buf+        attributes         <- (#peek CREDENTIAL, Attributes) buf+        targetAlias        <- (#peek CREDENTIAL, TargetAlias) buf+        userName           <- (#peek CREDENTIAL, UserName) buf+        return $ CREDENTIAL flags type' targetName comment lastWritten credentialBlobSize credentialBlob persist attributeCount attributes targetAlias userName++type CRED_PROTECTION_TYPE = DWORD++cRED_TYPE_GENERIC :: DWORD+cRED_TYPE_GENERIC = 1++cRED_PERSIST_LOCAL_MACHINE :: DWORD+cRED_PERSIST_LOCAL_MACHINE = 2++eRROR_NOT_FOUND :: ErrCode+eRROR_NOT_FOUND = #const ERROR_NOT_FOUND++eRROR_INSUFFICIENT_BUFFER :: ErrCode+eRROR_INSUFFICIENT_BUFFER = #const ERROR_INSUFFICIENT_BUFFER++foreign import ccall unsafe "CredReadW" c_CredRead :: LPCTSTR -> DWORD -> DWORD -> Ptr (Ptr CREDENTIAL) -> IO BOOL++foreign import ccall unsafe "CredWriteW" c_CredWrite :: Ptr CREDENTIAL -> DWORD -> IO BOOL++foreign import ccall unsafe "CredDeleteW" c_CredDelete :: LPCTSTR -> DWORD -> DWORD -> IO BOOL++foreign import ccall unsafe "CredFree" c_CredFree :: Ptr CREDENTIAL -> IO ()++foreign import ccall unsafe "CredProtectW" c_CredProtect :: BOOL -> LPTSTR -> DWORD -> LPTSTR -> Ptr DWORD -> Ptr CRED_PROTECTION_TYPE -> IO BOOL++foreign import ccall unsafe "CredUnprotectW" c_CredUnprotect :: BOOL -> LPTSTR -> DWORD -> LPTSTR -> Ptr DWORD -> IO BOOL
+ src/System/CredentialStore/Windows.hs view
@@ -0,0 +1,92 @@+module System.CredentialStore.Windows+    ( CredentialStore+    , getCredential+    , putCredential+    , deleteCredential+    , withCredentialStore+    ) where++import Control.Exception.Safe+import Control.Monad+import Data.ByteArray+import Foreign+import System.Win32.Time+import System.Win32.Types++import System.CredentialStore.WinTypes++data CredentialStore = CredentialStore++withCredentialStore :: (CredentialStore -> IO a) -> IO a+withCredentialStore f = f CredentialStore++getCredential :: ByteArray ba => CredentialStore -> String -> IO (Maybe ba)+getCredential _ name =+    withTString name $ \tstr ->+    alloca $ \pptr -> do+        result <- c_CredRead tstr cRED_TYPE_GENERIC 0 pptr+        if result+            then do+                ptr <- peek pptr+                cred <- finally+                  (do+                    rec <- peek ptr+                    decryptCredential (castPtr $ crCredentialBlob rec, crCredentialBlobSize rec)+                  ) (c_CredFree ptr)+                return $ Just cred+            else do+                errCode <- getLastError+                unless (errCode == eRROR_NOT_FOUND) $ failWith "CredRead" errCode+                return Nothing++putCredential :: ByteArrayAccess ba => CredentialStore -> String -> ba -> IO ()+putCredential _ name value =+    withEncryptedCredential value $ \(val, len) ->+    withTString name $ \tstr ->+    withTString "" $ \emptystr ->+    alloca $ \rec -> do+        poke rec CREDENTIAL+            { crFlags = 0+            , crType = cRED_TYPE_GENERIC+            , crTargetName = tstr+            , crComment = emptystr+            , crLastWritten = FILETIME 0+            , crCredentialBlobSize = len+            , crCredentialBlob = castPtr val+            , crPersist = cRED_PERSIST_LOCAL_MACHINE+            , crAttributeCount = 0+            , crAttributes = nullPtr+            , crTargetAlias = emptystr+            , crUserName = emptystr+            }+        failIfFalse_ "CredWrite" $ c_CredWrite rec 0++deleteCredential :: CredentialStore -> String -> IO ()+deleteCredential _ name = withTString name $ \tstr -> failIfFalse_ "CredDelete" $ c_CredDelete tstr cRED_TYPE_GENERIC 0++withEncryptedCredential :: ByteArrayAccess ba => ba -> ((LPTSTR, DWORD) -> IO a) -> IO a+withEncryptedCredential value f =+    withByteArray value $ \val ->+    alloca $ \protType ->+    alloca $ \sizeptr -> do+        let len = fromIntegral $ Data.ByteArray.length value+        poke sizeptr 0+        ret <- c_CredProtect True val len nullPtr sizeptr protType+        errCode <- getLastError+        unless (not ret && errCode == eRROR_INSUFFICIENT_BUFFER) $ failWith "CredProtect(NULL)" errCode+        needed <- peek sizeptr+        allocaBytes (fromIntegral needed * 2) $ \outputPtr -> do+            failIfFalse_ "CredProtect" $ c_CredProtect True val len outputPtr sizeptr protType+            outputLen <- peek sizeptr+            f (outputPtr, outputLen * 2)++decryptCredential :: ByteArray ba => (LPTSTR, DWORD) -> IO ba+decryptCredential (val, len) =+    alloca $ \sizeptr -> do+        poke sizeptr 0+        ret <- c_CredUnprotect True val len nullPtr sizeptr+        errCode <- getLastError+        unless (not ret && errCode == eRROR_INSUFFICIENT_BUFFER) $ failWith "CredUnprotect(NULL)" errCode+        needed <- peek sizeptr+        create (fromIntegral needed) $ \outputPtr ->+            failIfFalse_ "CredUnprotect" $ c_CredUnprotect True val len outputPtr sizeptr
+ test/Spec.hs view
@@ -0,0 +1,25 @@+import Test.Tasty+import Test.Tasty.HUnit+import qualified Data.ByteString.Char8 as BS8++import System.CredentialStore++main :: IO ()+main = defaultMain tests++tests :: TestTree+tests = testGroup "Credential store"+    [ testCase "Save-load-delete credential" testCred+    ]++testCred :: Assertion+testCred = withCredentialStore $ \store -> do+    putCredential store credentialName credentialValue+    v <- getCredential store credentialName+    assertEqual "value don't match" (Just credentialValue) v+    deleteCredential store credentialName+    v' <- getCredential store credentialName+    assertEqual "value not deleted" Nothing (v' :: Maybe BS8.ByteString)+    where+    credentialName = "credential-store-test"+    credentialValue = BS8.pack "foobar"