M7: Client Code Quality
M7: Client Code Quality
Poor code quality leads to buffer overflows, format string vulnerabilities, and other code-level issues that can be exploited.
// iOS - Code quality best practices
class CodeQualityManager {
// VULNERABLE: Common code quality issues
class PoorCodeQuality {
// Bad: Force unwrapping
func riskyOperation(data: Data?) {
let result = data! // Crash if nil
}
// Bad: No input validation
func processUserInput(_ input: String) {
let query = "SELECT * FROM users WHERE name = '\(input)'" // SQL injection
}
// Bad: Memory management issues
func leakMemory() {
class Node {
var next: Node?
var data: Data
init(data: Data) { self.data = data }
}
let node1 = Node(data: Data())
let node2 = Node(data: Data())
node1.next = node2
node2.next = node1 // Retain cycle
}
}
// SECURE: High-quality secure code
class HighQualityCode {
// Safe unwrapping with proper error handling
func safeOperation(data: Data?) throws -> ProcessedData {
guard let data = data else {
throw DataError.missingData
}
guard data.count >= minimumDataSize else {
throw DataError.invalidSize
}
return try processData(data)
}
// Input validation and sanitization
func processUserInput(_ input: String) throws -> QueryResult {
// Validate input
let sanitized = sanitizeInput(input)
guard isValidInput(sanitized) else {
throw ValidationError.invalidInput
}
// Use parameterized queries
let statement = try database.prepare(
"SELECT * FROM users WHERE name = ?"
)
statement.bind(sanitized)
return try statement.execute()
}
// Proper memory management
class SecureDataHandler {
private var sensitiveData: Data?
init(data: Data) {
self.sensitiveData = data
}
deinit {
// Clear sensitive data from memory
if var data = sensitiveData {
data.withUnsafeMutableBytes { bytes in
memset_s(bytes.baseAddress, bytes.count, 0, bytes.count)
}
}
}
func processData() throws -> Result {
guard let data = sensitiveData else {
throw DataError.noData
}
// Use autoreleasepool for memory-intensive operations
return try autoreleasepool {
try performProcessing(on: data)
}
}
}
// Thread safety
class ThreadSafeCounter {
private let queue = DispatchQueue(
label: "com.app.counter",
attributes: .concurrent
)
private var _value = 0
var value: Int {
queue.sync { _value }
}
func increment() {
queue.async(flags: .barrier) {
self._value += 1
}
}
}
}
}