快速对象的安全内存

kgr*_*nek 27 security macos memory-management ios swift

我正在编写一个需要在内存中处理私钥的快速应用程序.由于这些对象的敏感性,当对象被释放时,需要清除密钥(也称为全零),并且内存不能被分页到磁盘(通常使用mlock()完成).

在Objective-C中,您可以提供自定义CFAllocator对象,该对象允许您使用自己的函数来分配/释放/重新分配对象使用的内存.

因此,一种解决方案是在objective-c中实现"SecureData"对象,该对象使用自定义CFAllocator(也在objective-c中)内部创建NSMutableData对象.

但是,有没有办法为纯swift对象提供自己的自定义内存分配函数(例如,struct或[UInt8])?或者是否有更好的"适当"方式在swift中实现这样的安全内存?

Air*_*ity 36

如果你想完全控制你自己分配的内存区域,你可以使用UnsafePointer和co:

// allocate enough memory for ten Ints
var ump = UnsafeMutablePointer<Int>.alloc(10)
// memory is in an uninitialized raw state

// initialize that memory with Int objects
// (here, from a collection)
ump.initializeFrom(reverse(0..<10))

// memory property gives you access to the underlying value
ump.memory // 9

// UnsafeMutablePointer acts like an IndexType
ump.successor().memory // 8
// and it has a subscript, but it's not a CollectionType
ump[3] // = 6

// wrap it in an UnsafeMutableBufferPointer to treat it
// like a collection (or UnsafeBufferPointer if you don't
// need to be able to alter the values)
let col = UnsafeMutableBufferPointer(start: ump, count: 10)
col[3] = 99
println(",".join(map(col,toString)))
// prints 9,8,7,99,5,4,3,2,1,0

ump.destroy(10)
// now the allocated memory is back in a raw state
// you could re-allocate it...
ump.initializeFrom(0..<10)
ump.destroy(10)

// when you're done, deallocate the memory
ump.dealloc(10)
Run Code Online (Sandbox Code Playgroud)

您还可以UnsafePointer指向其他内存,例如您通过某些C API交付的内存.

UnsafePointer可以传递给C函数,该函数接受指向连续内存块的指针.因此,为了您的目的,您可以将此指针传递给以下函数mlock:

let count = 10
let ump = UnsafeMutablePointer.allocate<Int>(count)
mlock(ump, UInt(sizeof(Int) * count))
// initialize, use, and destroy the memory
munlock(ump, UInt(sizeof(Int) * count))
ump.dealloc(count)
Run Code Online (Sandbox Code Playgroud)

您甚至可以拥有自己的自定义类型:

struct MyStruct {
    let a: Int
    let b: Int
}

var pointerToStruct = UnsafeMutablePointer<MyStruct>.alloc(1)
pointerToStruct.initialize(MyStruct(a: 1, b: 2))
pointerToStruct.memory.b  // 2
pointerToStruct.destroy()
pointerToStruct.dealloc(1)
Run Code Online (Sandbox Code Playgroud)

但是请注意,如果使用类,甚至数组或字符串(或包含它们的结构)执行此操作,您将在内存中保存的所有内容都指向这些对象分配和拥有的其他内存.如果这对你很重要(即你正在为这个记忆做一些特别的事情,比如保护它,在你的例子中),这可能不是你想要的.

因此,您需要使用固定大小的对象,或者进一步使用UnsafePointer以保存指向更多内存区域的指针.如果它们不需要动态调整大小,那么只需一个不安全指针的分配(可能包含在UnsafeBufferPointer一个集合接口中)就可以完成.

如果您需要更多动态行为,下面是一个非常简单的集合实现,可以根据需要调整大小,可以增强以涵盖特殊的内存处理逻辑:

// Note this is a class not a struct, so it does NOT have value semantics,
// changing a copy changes all copies.
public class UnsafeCollection<T> {
    private var _len: Int = 0
    private var _buflen: Int = 0
    private var _buf: UnsafeMutablePointer<T> = nil

    public func removeAll(keepCapacity: Bool = false) {
        _buf.destroy(_len)
        _len = 0
        if !keepCapacity {
            _buf.dealloc(_buflen)
            _buflen = 0
            _buf = nil
        }
    }

    public required init() { }
    deinit { self.removeAll(keepCapacity: false) }

    public var count: Int { return _len }
    public var isEmpty: Bool { return _len == 0 }
}
Run Code Online (Sandbox Code Playgroud)

为了满足要求MutableCollectionType(即CollectionType加上可分配的下标):

extension UnsafeCollection: MutableCollectionType {
    typealias Index = Int
    public var startIndex: Int { return 0 }
    public var endIndex: Int { return _len }

    public subscript(idx: Int) -> T {
        get {
            precondition(idx < _len)
            return _buf[idx]
        }
        set(newElement) {
            precondition(idx < _len)
            let ptr = _buf.advancedBy(idx)
            ptr.destroy()
            ptr.initialize(newElement)
        }
    }

    typealias Generator = IndexingGenerator<UnsafeCollection>
    public func generate() -> Generator {
        return Generator(self)
    }
}
Run Code Online (Sandbox Code Playgroud)

并且ExtensibleCollectionType,为了实现动态增长:

extension UnsafeCollection: ExtensibleCollectionType {
    public func reserveCapacity(n: Index.Distance) {
        if n > _buflen {
            let newBuf = UnsafeMutablePointer<T>.alloc(n)
            newBuf.moveInitializeBackwardFrom(_buf, count: _len)
            _buf.dealloc(_buflen)
            _buf = newBuf
            _buflen = n
        }
    }

    public func append(x: T) {
        if _len == _buflen {
            reserveCapacity(Int(Double(_len) * 1.6) + 1)
        }
        _buf.advancedBy(_len++).initialize(x)
    }

    public func extend<S: SequenceType where S.Generator.Element == T>
      (newElements: S) {
        var g = newElements.generate()
        while let x: T = g.next() {
            self.append(x)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)