1/*
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3 *
4 * This code is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License version 2 only, as
6 * published by the Free Software Foundation.  Oracle designates this
7 * particular file as subject to the "Classpath" exception as provided
8 * by Oracle in the LICENSE file that accompanied this code.
9 *
10 * This code is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
13 * version 2 for more details (a copy is included in the LICENSE file that
14 * accompanied this code).
15 *
16 * You should have received a copy of the GNU General Public License version
17 * 2 along with this work; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19 *
20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21 * or visit www.oracle.com if you need additional information or have any
22 * questions.
23 */
24
25/*
26 *
27 *  (C) Copyright IBM Corp. 1999 All Rights Reserved.
28 *  Copyright 1997 The Open Group Research Institute.  All rights reserved.
29 */
30
31package sun.security.krb5.internal;
32
33import sun.security.krb5.Asn1Exception;
34import sun.security.krb5.Config;
35import sun.security.krb5.KrbException;
36import sun.security.util.DerInputStream;
37import sun.security.util.DerOutputStream;
38import sun.security.util.DerValue;
39
40import java.io.IOException;
41import java.time.Instant;
42import java.util.Calendar;
43import java.util.Date;
44import java.util.TimeZone;
45
46/**
47 * Implements the ASN.1 KerberosTime type. This is an immutable class.
48 *
49 * {@code KerberosTime ::= GeneralizedTime} -- with no fractional seconds
50 *
51 * The timestamps used in Kerberos are encoded as GeneralizedTimes. A
52 * KerberosTime value shall not include any fractional portions of the
53 * seconds.  As required by the DER, it further shall not include any
54 * separators, and it shall specify the UTC time zone (Z).
55 *
56 * <p>
57 * This definition reflects the Network Working Group RFC 4120
58 * specification available at
59 * <a href="http://www.ietf.org/rfc/rfc4120.txt">
60 * http://www.ietf.org/rfc/rfc4120.txt</a>.
61 *
62 * The implementation also includes the microseconds info so that the
63 * same class can be used as a precise timestamp in Authenticator etc.
64 */
65
66public class KerberosTime {
67
68    private final long kerberosTime; // milliseconds since epoch, Date.getTime()
69    private final int  microSeconds; // last 3 digits of the real microsecond
70
71    // The time when this class is loaded. Used in setNow()
72    private static long initMilli = System.currentTimeMillis();
73    private static long initMicro = System.nanoTime() / 1000;
74
75    private static boolean DEBUG = Krb5.DEBUG;
76
77    // Do not make this public. It's a little confusing that micro
78    // is only the last 3 digits of microsecond.
79    private KerberosTime(long time, int micro) {
80        kerberosTime = time;
81        microSeconds = micro;
82    }
83
84    /**
85     * Creates a KerberosTime object from milliseconds since epoch.
86     */
87    public KerberosTime(long time) {
88        this(time, 0);
89    }
90
91    // This constructor is used in the native code
92    // src/windows/native/sun/security/krb5/NativeCreds.c
93    public KerberosTime(String time) throws Asn1Exception {
94        this(toKerberosTime(time), 0);
95    }
96
97    private static long toKerberosTime(String time) throws Asn1Exception {
98        // ASN.1 GeneralizedTime format:
99
100        // "19700101000000Z"
101        //  |   | | | | | |
102        //  0   4 6 8 | | |
103        //           10 | |
104        //             12 |
105        //               14
106
107        if (time.length() != 15)
108            throw new Asn1Exception(Krb5.ASN1_BAD_TIMEFORMAT);
109        if (time.charAt(14) != 'Z')
110            throw new Asn1Exception(Krb5.ASN1_BAD_TIMEFORMAT);
111        int year = Integer.parseInt(time.substring(0, 4));
112        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
113        calendar.clear(); // so that millisecond is zero
114        calendar.set(year,
115                     Integer.parseInt(time.substring(4, 6)) - 1,
116                     Integer.parseInt(time.substring(6, 8)),
117                     Integer.parseInt(time.substring(8, 10)),
118                     Integer.parseInt(time.substring(10, 12)),
119                     Integer.parseInt(time.substring(12, 14)));
120        return calendar.getTimeInMillis();
121    }
122
123    /**
124     * Creates a KerberosTime object from a Date object.
125     */
126    public KerberosTime(Date time) {
127        this(time.getTime(), 0);
128    }
129
130    /**
131     * Creates a KerberosTime object from an Instant object
132     */
133    public KerberosTime(Instant instant) {
134        this(instant.getEpochSecond()*1000 + instant.getNano()/1000000L,
135                instant.getNano()/1000%1000);
136    }
137
138    /**
139     * Creates a KerberosTime object for now. It uses System.nanoTime()
140     * to get a more precise time than "new Date()".
141     */
142    public static KerberosTime now() {
143        long newMilli = System.currentTimeMillis();
144        long newMicro = System.nanoTime() / 1000;
145        long microElapsed = newMicro - initMicro;
146        long calcMilli = initMilli + microElapsed/1000;
147        if (calcMilli - newMilli > 100 || newMilli - calcMilli > 100) {
148            if (DEBUG) {
149                System.out.println("System time adjusted");
150            }
151            initMilli = newMilli;
152            initMicro = newMicro;
153            return new KerberosTime(newMilli, 0);
154        } else {
155            return new KerberosTime(calcMilli, (int)(microElapsed % 1000));
156        }
157    }
158
159    /**
160     * Returns a string representation of KerberosTime object.
161     * @return a string representation of this object.
162     */
163    public String toGeneralizedTimeString() {
164        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
165        calendar.clear();
166
167        calendar.setTimeInMillis(kerberosTime);
168        return String.format("%04d%02d%02d%02d%02d%02dZ",
169                calendar.get(Calendar.YEAR),
170                calendar.get(Calendar.MONTH) + 1,
171                calendar.get(Calendar.DAY_OF_MONTH),
172                calendar.get(Calendar.HOUR_OF_DAY),
173                calendar.get(Calendar.MINUTE),
174                calendar.get(Calendar.SECOND));
175    }
176
177    /**
178     * Encodes this object to a byte array.
179     * @return a byte array of encoded data.
180     * @exception Asn1Exception if an error occurs while decoding an ASN1 encoded data.
181     * @exception IOException if an I/O error occurs while reading encoded data.
182     */
183    public byte[] asn1Encode() throws Asn1Exception, IOException {
184        DerOutputStream out = new DerOutputStream();
185        out.putGeneralizedTime(this.toDate());
186        return out.toByteArray();
187    }
188
189    public long getTime() {
190        return kerberosTime;
191    }
192
193    public Date toDate() {
194        return new Date(kerberosTime);
195    }
196
197    public int getMicroSeconds() {
198        int temp_int = (int) ((kerberosTime % 1000L) * 1000L);
199        return temp_int + microSeconds;
200    }
201
202    /**
203     * Returns a new KerberosTime object with the original seconds
204     * and the given microseconds.
205     */
206    public KerberosTime withMicroSeconds(int usec) {
207        return new KerberosTime(
208                kerberosTime - kerberosTime%1000L + usec/1000L,
209                usec%1000);
210    }
211
212    private boolean inClockSkew(int clockSkew) {
213        return java.lang.Math.abs(kerberosTime - System.currentTimeMillis())
214                <= clockSkew * 1000L;
215    }
216
217    public boolean inClockSkew() {
218        return inClockSkew(getDefaultSkew());
219    }
220
221    public boolean greaterThanWRTClockSkew(KerberosTime time, int clockSkew) {
222        if ((kerberosTime - time.kerberosTime) > clockSkew * 1000L)
223            return true;
224        return false;
225    }
226
227    public boolean greaterThanWRTClockSkew(KerberosTime time) {
228        return greaterThanWRTClockSkew(time, getDefaultSkew());
229    }
230
231    public boolean greaterThan(KerberosTime time) {
232        return kerberosTime > time.kerberosTime ||
233            kerberosTime == time.kerberosTime &&
234                    microSeconds > time.microSeconds;
235    }
236
237    public boolean equals(Object obj) {
238        if (this == obj) {
239            return true;
240        }
241
242        if (!(obj instanceof KerberosTime)) {
243            return false;
244        }
245
246        return kerberosTime == ((KerberosTime)obj).kerberosTime &&
247                microSeconds == ((KerberosTime)obj).microSeconds;
248    }
249
250    public int hashCode() {
251        int result = 37 * 17 + (int)(kerberosTime ^ (kerberosTime >>> 32));
252        return result * 17 + microSeconds;
253    }
254
255    public boolean isZero() {
256        return kerberosTime == 0 && microSeconds == 0;
257    }
258
259    public int getSeconds() {
260        return (int) (kerberosTime / 1000L);
261    }
262
263    /**
264     * Parse (unmarshal) a kerberostime from a DER input stream.  This form
265     * parsing might be used when expanding a value which is part of
266     * a constructed sequence and uses explicitly tagged type.
267     *
268     * @exception Asn1Exception on error.
269     * @param data the Der input stream value, which contains
270     *             one or more marshaled value.
271     * @param explicitTag tag number.
272     * @param optional indicates if this data field is optional
273     * @return an instance of KerberosTime.
274     *
275     */
276    public static KerberosTime parse(
277            DerInputStream data, byte explicitTag, boolean optional)
278            throws Asn1Exception, IOException {
279        if ((optional) && (((byte)data.peekByte() & (byte)0x1F)!= explicitTag))
280            return null;
281        DerValue der = data.getDerValue();
282        if (explicitTag != (der.getTag() & (byte)0x1F))  {
283            throw new Asn1Exception(Krb5.ASN1_BAD_ID);
284        }
285        else {
286            DerValue subDer = der.getData().getDerValue();
287            Date temp = subDer.getGeneralizedTime();
288            return new KerberosTime(temp.getTime(), 0);
289        }
290    }
291
292    public static int getDefaultSkew() {
293        int tdiff = Krb5.DEFAULT_ALLOWABLE_CLOCKSKEW;
294        try {
295            if ((tdiff = Config.getInstance().getIntValue(
296                    "libdefaults", "clockskew"))
297                        == Integer.MIN_VALUE) {   //value is not defined
298                tdiff = Krb5.DEFAULT_ALLOWABLE_CLOCKSKEW;
299            }
300        } catch (KrbException e) {
301            if (DEBUG) {
302                System.out.println("Exception in getting clockskew from " +
303                                   "Configuration " +
304                                   "using default value " +
305                                   e.getMessage());
306            }
307        }
308        return tdiff;
309    }
310
311    public String toString() {
312        return toGeneralizedTimeString();
313    }
314}
315