aboutsummaryrefslogtreecommitdiff
path: root/4.1/get_mail.rb
blob: 8cbbb1ff584416e9a3be7b6fe3801a2e708bad2f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/usr/bin/env ruby

require 'net/http'
require 'uri'
require 'json'

def get_ticket(un, tgt, sv)
  uri = URI.parse("http://localhost:4567/ticket")
  header = {'Content-Type': 'text/json'}

  login = {
    "username": un,
    "ticket": tgt,
    "service": sv
  }

  http = Net::HTTP.new(uri.host, uri.port)
  request = Net::HTTP::Post.new(uri.request_uri, header)
  request.body = login.to_json

  response = http.request(request)
  response.body
end

def ticket_valid?(ticket)
  now = Time.now.to_i
  timeStart = ticket["timestamp"]
  timeEnd = ticket["timestamp"] + ticket["lifespan"]
  now >= timeStart && now < timeEnd
end

def update_keytab!
  File.open(".keytab", "w") do |f|
    f.puts Tickets.map { |s, p| [s, *p.values].join(?:) }
  end
end

print "Username: "; un = gets.strip
print "Mailserver: "; ms = gets.strip

unless File.exist?(".keytab")
  puts "No keytab, please kinit"
  exit 1
end

Tickets = File.readlines(".keytab").map { |l|
  a = l.strip.split(?:)
  [a[0], {
    "lifespan" => a[1].to_i,
    "timestamp" => a[2].to_i,
    "ticket" => a[3]
  }]
}.to_h

unless Tickets.keys.include?(ms) && ticket_valid?(Tickets[ms])
  if Tickets.keys.include?("_TGS") && ticket_valid?(Tickets["_TGS"])
    packet = get_ticket(un, Tickets["_TGS"]["ticket"], ms).split(?:)
    Tickets[ms] = {
      "lifespan" => packet[0].to_i,
      "timestamp" => packet[1].to_i,
      "ticket" => packet[2]
    }
    update_keytab!
  else
    puts "No Ticket Granting Ticket, please kinit"
    exit 1
  end
end

ticket = Tickets[ms]["ticket"]

uri = URI.parse("http://localhost:4568/login")
header = {'Content-Type': 'text/json'}

login = {
  "username": un,
  "ticket": ticket
}

http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri, header)
request.body = login.to_json

response = http.request(request)
puts response.body