// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Asking for the master password through pinentry. //! //! pinentry is GnuPG's password dialog: a separate program, in a flavor for //! each desktop and one for the terminal, spoken to over its standard input //! and output with the Assuan protocol. Each command gets a line back //! beginning `OK` or `ERR`; `GETPIN` first sends the password as a `D` line, //! with `%`, CR and LF percent-escaped. Using it means the password is asked //! for in the same dialog GnuPG itself would use, on whatever display or //! terminal the request came from, and never passes through bwgpg's own //! terminal handling. const std = @import("std"); const Allocator = std.mem.Allocator; const Io = std.Io; const testing = std.testing; pub const Error = error{ /// The dialog was cancelled or closed. Cancelled, /// pinentry answered something other than the protocol. ProtocolError, /// pinentry refused a command, for a reason other than cancelling. PinentryFailed, /// A confirmation was answered no. NotConfirmed, }; pub const Request = struct { title: []const u8 = "bwgpg", description: []const u8, prompt: []const u8 = "Master password:", /// Shown above the prompt; how a retry says the last attempt was wrong. error_text: ?[]const u8 = null, /// For a terminal pinentry: which terminal, and what kind. tty_name: ?[]const u8 = null, tty_type: ?[]const u8 = null, }; /// Assuan error codes, in their low 16 bits; the high bits carry the error /// source, which varies. GPG_ERR_CANCELED is the dialog closed or cancelled, /// GPG_ERR_NOT_CONFIRMED a confirmation answered with its "not OK" button. const gpg_err_canceled = 99; const gpg_err_not_confirmed = 114; fn writeEscaped(w: *Io.Writer, text: []const u8) Io.Writer.Error!void { for (text) |c| switch (c) { '%' => try w.writeAll("%25"), '\n' => try w.writeAll("%0A"), '\r' => try w.writeAll("%0D"), else => try w.writeByte(c), }; } /// One line from pinentry, without its line ending. fn readLine(r: *Io.Reader) Error![]const u8 { const line = r.takeDelimiterInclusive('\n') catch return error.ProtocolError; return std.mem.trimEnd(u8, line, "\r\n"); } /// Reads lines until `OK` or `ERR`, appending the contents of any `D` lines /// to `data`. fn awaitOk(gpa: Allocator, r: *Io.Reader, data: ?*std.ArrayList(u8)) (Error || Allocator.Error)!void { while (true) { const line = try readLine(r); if (std.mem.eql(u8, line, "OK") or std.mem.startsWith(u8, line, "OK ")) return; if (std.mem.startsWith(u8, line, "ERR ")) { const rest = line[4..]; const end = std.mem.findScalar(u8, rest, ' ') orelse rest.len; const code = std.fmt.parseInt(u32, rest[0..end], 10) catch return error.PinentryFailed; return switch (code & 0xffff) { gpg_err_canceled => error.Cancelled, gpg_err_not_confirmed => error.NotConfirmed, else => error.PinentryFailed, }; } if (std.mem.startsWith(u8, line, "D ")) { const list = data orelse return error.ProtocolError; try percentDecodeAppend(gpa, list, line[2..]); continue; } // Status lines and comments carry nothing needed here. if (std.mem.startsWith(u8, line, "S ") or std.mem.startsWith(u8, line, "#") or line.len == 0) continue; return error.ProtocolError; } } fn percentDecodeAppend(gpa: Allocator, list: *std.ArrayList(u8), text: []const u8) (Error || Allocator.Error)!void { var i: usize = 0; while (i < text.len) : (i += 1) { if (text[i] == '%') { if (text.len - i < 3) return error.ProtocolError; const byte = std.fmt.parseInt(u8, text[i + 1 .. i + 3], 16) catch return error.ProtocolError; try list.append(gpa, byte); i += 2; } else { try list.append(gpa, text[i]); } } } /// Tells a terminal pinentry which terminal to use. OPTION's argument is /// `name=value`, with only the value escaped, so it is written here rather /// than through `command`. fn sendTtyOptions(gpa: Allocator, r: *Io.Reader, w: *Io.Writer, tty_name: ?[]const u8, tty_type: ?[]const u8) (Error || Allocator.Error)!void { const io_err = error.ProtocolError; const Option = struct { name: []const u8, value: ?[]const u8 }; const options = [_]Option{ .{ .name = "ttyname", .value = tty_name }, .{ .name = "ttytype", .value = tty_type }, }; for (options) |opt| { const value = opt.value orelse continue; w.print("OPTION {s}=", .{opt.name}) catch return io_err; writeEscaped(w, value) catch return io_err; w.writeByte('\n') catch return io_err; w.flush() catch return io_err; // An option the pinentry does not know is not a reason to stop. awaitOk(gpa, r, null) catch |err| switch (err) { error.PinentryFailed => {}, else => return err, }; } } fn command(w: *Io.Writer, verb: []const u8, arg: ?[]const u8) Io.Writer.Error!void { try w.writeAll(verb); if (arg) |a| { try w.writeByte(' '); try writeEscaped(w, a); } try w.writeByte('\n'); try w.flush(); } /// Holds a conversation with a pinentry already running on `r` and `w`, and /// returns the password, allocated from `gpa`. The caller wipes and frees it. /// /// `gpa` should be the locked allocator: this is where the password first /// exists in bwgpg's memory. pub fn converse(gpa: Allocator, r: *Io.Reader, w: *Io.Writer, req: Request) (Error || Allocator.Error)![]u8 { const io_err = error.ProtocolError; // The greeting. try awaitOk(gpa, r, null); try sendTtyOptions(gpa, r, w, req.tty_name, req.tty_type); const Setting = struct { verb: []const u8, arg: ?[]const u8 }; const settings = [_]Setting{ .{ .verb = "SETTITLE", .arg = req.title }, .{ .verb = "SETDESC", .arg = req.description }, .{ .verb = "SETPROMPT", .arg = req.prompt }, .{ .verb = "SETERROR", .arg = req.error_text }, }; for (settings) |s| { const arg = s.arg orelse continue; command(w, s.verb, arg) catch return io_err; try awaitOk(gpa, r, null); } var pin: std.ArrayList(u8) = .empty; errdefer { std.crypto.secureZero(u8, pin.allocatedSlice()); pin.deinit(gpa); } command(w, "GETPIN", null) catch return io_err; try awaitOk(gpa, r, &pin); command(w, "BYE", null) catch {}; return pin.toOwnedSlice(gpa); } pub const ConfirmRequest = struct { title: []const u8 = "bwgpg", description: []const u8, ok: []const u8 = "Sign", cancel: []const u8 = "Deny", tty_name: ?[]const u8 = null, tty_type: ?[]const u8 = null, }; /// Asks a yes-or-no question of a pinentry already running on `r` and `w`, /// with `CONFIRM`: true for the OK button, false for cancel, "not OK", or /// the dialog being closed. pub fn converseConfirm(gpa: Allocator, r: *Io.Reader, w: *Io.Writer, req: ConfirmRequest) (Error || Allocator.Error)!bool { const io_err = error.ProtocolError; try awaitOk(gpa, r, null); try sendTtyOptions(gpa, r, w, req.tty_name, req.tty_type); const Setting = struct { verb: []const u8, arg: []const u8 }; const settings = [_]Setting{ .{ .verb = "SETTITLE", .arg = req.title }, .{ .verb = "SETDESC", .arg = req.description }, .{ .verb = "SETOK", .arg = req.ok }, .{ .verb = "SETCANCEL", .arg = req.cancel }, }; for (settings) |s| { command(w, s.verb, s.arg) catch return io_err; try awaitOk(gpa, r, null); } command(w, "CONFIRM", null) catch return io_err; const yes = if (awaitOk(gpa, r, null)) true else |err| switch (err) { error.Cancelled, error.NotConfirmed => false, else => return err, }; command(w, "BYE", null) catch {}; return yes; } /// Runs `program` with its standard input and output as the two ends of an /// Assuan conversation, and holds `conversation` on them. fn withPinentry( io: Io, program: []const u8, environ: ?*const std.process.Environ.Map, comptime T: type, context: anytype, comptime conversation: fn (@TypeOf(context), *Io.Reader, *Io.Writer) T, ) (std.process.SpawnError || @typeInfo(T).error_union.error_set)!@typeInfo(T).error_union.payload { var child = try std.process.spawn(io, .{ .argv = &.{program}, .environ_map = environ, .stdin = .pipe, .stdout = .pipe, .stderr = .ignore, .create_no_window = true, }); defer { if (child.stdin) |f| f.close(io); child.stdin = null; _ = child.wait(io) catch {}; } var in_buf: [2048]u8 = undefined; var out_buf: [1024]u8 = undefined; var reader = child.stdout.?.reader(io, &in_buf); var writer = child.stdin.?.writer(io, &out_buf); defer std.crypto.secureZero(u8, &in_buf); return conversation(context, &reader.interface, &writer.interface); } /// Runs `program` and asks it a yes-or-no question. pub fn confirm( gpa: Allocator, io: Io, program: []const u8, environ: ?*const std.process.Environ.Map, req: ConfirmRequest, ) (Error || Allocator.Error || std.process.SpawnError)!bool { const Ctx = struct { gpa: Allocator, req: ConfirmRequest, fn run(c: @This(), r: *Io.Reader, w: *Io.Writer) (Error || Allocator.Error)!bool { return converseConfirm(c.gpa, r, w, c.req); } }; return withPinentry(io, program, environ, (Error || Allocator.Error)!bool, Ctx{ .gpa = gpa, .req = req }, Ctx.run); } /// Runs `program` and asks it for the password. /// /// `environ` is the environment pinentry runs in, which is how a graphical /// one finds the display and a terminal one finds the terminal: the agent /// passes the environment of whichever command asked it to unlock. pub fn getPin( gpa: Allocator, io: Io, program: []const u8, environ: ?*const std.process.Environ.Map, req: Request, ) (Error || Allocator.Error || std.process.SpawnError)![]u8 { const Ctx = struct { gpa: Allocator, req: Request, fn run(c: @This(), r: *Io.Reader, w: *Io.Writer) (Error || Allocator.Error)![]u8 { return converse(c.gpa, r, w, c.req); } }; return withPinentry(io, program, environ, (Error || Allocator.Error)![]u8, Ctx{ .gpa = gpa, .req = req }, Ctx.run); } test "a conversation, with an escaped password and noise between replies" { const gpa = testing.allocator; var r: Io.Reader = .fixed( "OK Pleased to meet you\n" ++ "OK\n" ++ // OPTION ttyname "ERR 83886254 Unknown option\n" ++ // OPTION ttytype "OK\n" ++ // SETTITLE "OK\n" ++ // SETDESC "# a comment\n" ++ "OK\n" ++ // SETPROMPT "S PASSWORD_FROM_CACHE\n" ++ "D pa%25ss%0Aword\n" ++ "OK\n", ); var out: [1024]u8 = undefined; var w: Io.Writer = .fixed(&out); const pin = try converse(gpa, &r, &w, .{ .description = "Unlock 50% of it\nplease", .tty_name = "/dev/pts/3", .tty_type = "xterm", }); defer gpa.free(pin); try testing.expectEqualStrings("pa%ss\nword", pin); const sent = w.buffered(); try testing.expect(std.mem.find(u8, sent, "SETDESC Unlock 50%25 of it%0Aplease\n") != null); try testing.expect(std.mem.find(u8, sent, "OPTION ttyname=/dev/pts/3\n") != null); try testing.expect(std.mem.endsWith(u8, sent, "GETPIN\nBYE\n")); } test "cancelling is told apart from failing" { const gpa = testing.allocator; var out: [1024]u8 = undefined; var r1: Io.Reader = .fixed("OK hi\nOK\nOK\nOK\nERR 83886179 Operation cancelled \n"); var w1: Io.Writer = .fixed(&out); try testing.expectError(error.Cancelled, converse(gpa, &r1, &w1, .{ .description = "d" })); var r2: Io.Reader = .fixed("OK hi\nERR 1 nope\n"); var w2: Io.Writer = .fixed(&out); try testing.expectError(error.PinentryFailed, converse(gpa, &r2, &w2, .{ .description = "d" })); var r3: Io.Reader = .fixed("OK hi\nOK\nOK\nOK\nD bad%4\nOK\n"); var w3: Io.Writer = .fixed(&out); try testing.expectError(error.ProtocolError, converse(gpa, &r3, &w3, .{ .description = "d" })); // pinentry going away mid-conversation. var r4: Io.Reader = .fixed("OK hi\nOK\n"); var w4: Io.Writer = .fixed(&out); try testing.expectError(error.ProtocolError, converse(gpa, &r4, &w4, .{ .description = "d" })); } test "a confirmation: yes, no, not OK, and a pinentry that fails" { const gpa = testing.allocator; var out: [1024]u8 = undefined; const req: ConfirmRequest = .{ .description = "Sign 100% of it?\nReally?" }; var r1: Io.Reader = .fixed("OK hi\nOK\nOK\nOK\nOK\nOK\nOK\n"); var w1: Io.Writer = .fixed(&out); try testing.expect(try converseConfirm(gpa, &r1, &w1, req)); const sent = w1.buffered(); try testing.expect(std.mem.find(u8, sent, "SETDESC Sign 100%25 of it?%0AReally?\n") != null); try testing.expect(std.mem.find(u8, sent, "SETOK Sign\nSETCANCEL Deny\nCONFIRM\n") != null); var r2: Io.Reader = .fixed("OK hi\nOK\nOK\nOK\nOK\nERR 83886179 Operation cancelled \n"); var w2: Io.Writer = .fixed(&out); try testing.expect(!try converseConfirm(gpa, &r2, &w2, req)); var r3: Io.Reader = .fixed("OK hi\nOK\nOK\nOK\nOK\nERR 83886194 Not confirmed \n"); var w3: Io.Writer = .fixed(&out); try testing.expect(!try converseConfirm(gpa, &r3, &w3, req)); var r4: Io.Reader = .fixed("OK hi\nOK\nOK\nOK\nOK\nERR 1 broken\n"); var w4: Io.Writer = .fixed(&out); try testing.expectError(error.PinentryFailed, converseConfirm(gpa, &r4, &w4, req)); }